1. 程式人生 > >spring-security-01

spring-security-01

web.xml

定義filter

  <filter>
      <filter-name>springSecurityFilterChain</filter-name> <!-- 名字必須固定是這個 -->
      <filter-class>
          org.springframework.web.filter.DelegatingFilterProxy
      </filter-class>
  </filter>
  <filter-mapping>
      <
filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

applicationContext.xml配置

    <!-- 表示現在的程式碼之中啟用Spring的安全配置 -->
    <security:global-method-security jsr250-annotations="enabled" secured-annotations="enabled"
/> <!-- 啟用安全配置操作,此時的配置將採用全自動的方式完成處理 --> <security:http auto-config="true" access-denied-page="/403.jsp"/> <!-- 配置授權管理器,所有可以使用到登入使用者資訊都可以在此處配置 --> <security:authentication-manager alias="authenticationManager"> <!-- 配置本次要使用的金泰的使用者名稱密碼 --> <
security:authentication-provider> <!-- 定義所有固定的使用者名稱和密碼的資訊 --> <security:user-service> <security:user name="admin" password="hello" authorities="ROLE_ADMIN,ROLE_USER"/> <security:user name="mldn" password="java" authorities="ROLE_USER"/> </security:user-service> </security:authentication-provider> </security:authentication-manager>

action實現

@Controller
@RequestMapping("/pages/back/message/*")
public class MessageAction {
    
    @RequestMapping("message_addPre")
    @Secured(value={"ROLE_ADMIN","ROLE_USER"})
    public ModelAndView addPre() {
        //取得登入使用者的詳細登入資訊
        UserDetails details = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("*** [username] "  + details.getUsername());
        System.out.println("*** [password] "  + details.getPassword());
        System.out.println("*** [authorities] "  + details.getAuthorities());
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/message_list.jsp");
        return mav;
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1>您好:${ sessionScope['SPRING_SECURITY_CONTEXT'].authentication.principal.username }</h1>
<h2>
    <security:authentication property="authorities" var="aut"/>
    角色: ${aut}

</h2>
<h2>
    <security:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
        判斷具有角色 :ROLE_ADMIN,ROLE_USER
    </security:authorize>
</h2>

</body>
</html>