Sping Security 4 Role Based Login Example(4)

来源:互联网 发布:通过域名查询服务器 编辑:程序博客网 时间:2024/06/10 19:21

一、项目结构

This tutorial explores Spring Security’s role based login. That means redirecting users to different URLs upon login according to their assigned roles.Basically what we have to do is to create a custom Success-Handler which will be responsible for redirecting the logged-in user to appropriate URL based on his/her role. Spring Security already provides SimpleUrlAuthenticationSuccessHandler which contains the generic logic for success handler. We will just extend this with our own redirect logic to achieve our goal.
1. 项目结构:

2. pom.xml文件如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.npf</groupId>  <artifactId>sping-security-role-based-login</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>sping-security-role-based-login Maven Webapp</name>  <url>http://maven.apache.org</url>  <properties><spring.version>4.1.6.RELEASE</spring.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  </properties>    <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.10</version>      <scope>test</scope>    </dependency>        <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.10</version>      <scope>test</scope>    </dependency>    <dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-jdbc</artifactId>    <version>${spring.version}</version></dependency><dependency>    <groupId>commons-logging</groupId>    <artifactId>commons-logging</artifactId>    <version>1.2</version></dependency><dependency>    <groupId>jstl</groupId>    <artifactId>jstl</artifactId>    <version>1.2</version></dependency><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis-spring</artifactId>    <version>1.3.0</version></dependency><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis</artifactId>    <version>3.4.0</version></dependency><dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>5.1.30</version></dependency><dependency>    <groupId>commons-dbcp</groupId>    <artifactId>commons-dbcp</artifactId>    <version>1.4</version></dependency><dependency>    <groupId>commons-io</groupId>    <artifactId>commons-io</artifactId>    <version>2.5</version></dependency><dependency>    <groupId>commons-fileupload</groupId>    <artifactId>commons-fileupload</artifactId>    <version>1.3.2</version></dependency><dependency>        <groupId>org.springframework.security</groupId>        <artifactId>spring-security-web</artifactId>        <version>4.0.1.RELEASE</version>    </dependency>        <dependency>        <groupId>org.springframework.security</groupId>        <artifactId>spring-security-config</artifactId>        <version>4.0.1.RELEASE</version>    </dependency>        <dependency>    <groupId>org.springframework.security</groupId>    <artifactId>spring-security-taglibs</artifactId>    <version>4.0.1.RELEASE</version></dependency>  </dependencies>    <profiles>  <profile>    <id>jdk-1.7</id>    <activation>        <activeByDefault>true</activeByDefault>        <jdk>1.7</jdk>    </activation>    <properties>        <maven.compiler.source>1.7</maven.compiler.source>        <maven.compiler.target>1.7</maven.compiler.target>        <maven.compiler.compilerVersion>1.7</maven.compiler.compilerVersion>    </properties></profile>   </profiles>  <build>    <finalName>sping-security-role-based-login</finalName>  </build></project>
3. spring-security.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/security"    xmlns:beans="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd    http://www.springframework.org/schema/security     http://www.springframework.org/schema/security/spring-security-4.0.xsd">        <beans:bean id="securityContextLogoutHandle"     class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"/><http auto-config="true" use-expressions="true"><intercept-url pattern="/" access="hasRole('USER')" />        <intercept-url pattern="/home" access="hasRole('USER')" />        <intercept-url pattern="/admin/**" access="hasRole('ADMIN')" />        <intercept-url pattern="/dba/**" access="hasRole('DBA')" />        <access-denied-handler error-page="/accessDenied" />        <form-login login-page="/login"         username-parameter="ssoId"         password-parameter="password"        login-processing-url="/login"          authentication-success-handler-ref="mySimpleUrlAuthenticationSuccessHandler"            authentication-failure-url="/authenticationFailure"/>    </http>      <authentication-manager >        <authentication-provider>            <user-service>                <user name="jack"  password="jack123"  authorities="ROLE_USER" />                <user name="admin" password="admin123" authorities="ROLE_ADMIN" />                <user name="dbaOnly" password="dba123" authorities="ROLE_DBA" />                <user name="dba" password="dba123" authorities="ROLE_ADMIN,ROLE_DBA" />            </user-service>        </authentication-provider>    </authentication-manager>        </beans:beans>
4. web.xml文件添加如下配置:
<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>
5. HelloWorldController:
package com.npf.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.Authentication;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controllerpublic class HelloWorldController {@Autowiredprivate SecurityContextLogoutHandler securityContextLogoutHandle;@RequestMapping(value = {"/home","/"}, method = RequestMethod.GET)public String homePage(ModelMap model) {Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();String userName = principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : principal.toString();model.addAttribute("user", userName);return "welcome";}@RequestMapping(value = "/admin/index", method = RequestMethod.GET)public String adminPage(ModelMap model) {Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();String userName = principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : principal.toString();model.addAttribute("user", userName);return "admin/index";}@RequestMapping(value = "/dba/index", method = RequestMethod.GET)public String dbaPage(ModelMap model) {Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();String userName = principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : principal.toString();model.addAttribute("user", userName);return "dba/index";}@RequestMapping(value = "/login", method = RequestMethod.GET)    public String loginPage() {        return "login";    }@RequestMapping(value = "/logout", method = RequestMethod.GET)public String logoutPage(HttpServletRequest request,HttpServletResponse response) {Authentication auth = SecurityContextHolder.getContext().getAuthentication();if (auth != null) {securityContextLogoutHandle.logout(request, response, auth);}return "redirect:/home";}@RequestMapping(value = "/accessDenied", method = RequestMethod.GET)public String accessDeniedPage(ModelMap model) {Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();String userName = principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : principal.toString();model.addAttribute("user", userName);return "accessDenied";}@RequestMapping(value = "/authenticationFailure", method = RequestMethod.GET)public String authenticationFailure(HttpServletRequest request){request.setAttribute("authenticationFailureResult", "failure");return "login";}}
5. MySimpleUrlAuthenticationSuccessHandler:
package com.npf.handler;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.web.DefaultRedirectStrategy;import org.springframework.security.web.RedirectStrategy;import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;import org.springframework.stereotype.Component;@Component("mySimpleUrlAuthenticationSuccessHandler")public class MySimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();@Overrideprotected void handle(HttpServletRequest request,HttpServletResponse response, Authentication authentication) throws IOException, ServletException {String targetUrl = determineTargetUrl(authentication);if (response.isCommitted()) {            System.out.println("Can't redirect");            return;        }        redirectStrategy.sendRedirect(request, response, targetUrl);}protected String determineTargetUrl(Authentication authentication) {        String url = "";        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();        List<String> roles = new ArrayList<String>();        for (GrantedAuthority a : authorities) {            roles.add(a.getAuthority());        }        if (roles.contains("ROLE_DBA")) {            url = "/dba/index";        } else if (roles.contains("ROLE_ADMIN")) {            url = "/admin/index";        } else if (roles.contains("ROLE_USER")) {            url = "/home";        } else {            url = "/accessDenied";        }        return url;    }}

二、测试

1. 访问主页: http://localhost:8080/sping-security-role-based-login/
因为没有权限访问主页,所以被定向到了登录页面:


2. 测试拥有"USER"权限登录页面定向情况:


登录成功后,你将会看到:

3. 测试拥有"ADMIN"权限登录页面定向情况:


登录成功后,你将会看到:

4. 测试拥有"DBA"权限登录页面定向情况:


登录成功后,你将会看到:

项目的源代码地址: https://github.com/spring-security/sping-security-role-based-login

参考文献:
1.Spring Security 4 Role Based Login Example
0 0
原创粉丝点击