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>

猜你喜欢

转载自www.cnblogs.com/blog-747674599/p/10061838.html
今日推荐