`

Spring Security 自定义登录验证与自定义回调地址

 
阅读更多
Spring Security 自定义登录验证与自定义回调地址

博客分类: spring
securityspring
Java代码 
1 配置文件 security-ns.xml 
    
     <?xml version="1.0" encoding="UTF-8"?> 
    <beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 
 
    //需要过滤不被拦截的请求 
    <security:http pattern="/openapi/**" security="none" /> 
    <security:http pattern="/useraccounts/userprofile.json" security="none" /> 
    <security:http pattern="/useraccounts/register**" security="none" /> 
    
     //entry-point-ref 配置自定义登录 
    <security:http auto-config="false" entry-point-ref="authenticationEntryPoint"> 
        <security:intercept-url pattern="/backManage/**" access="ROLE_BACK_USER" /> 
        <security:intercept-url pattern="/mall/**"       access="ROLE_BACK_USER" /> 
        <security:intercept-url pattern="/thirdUser/**"  access="ROLE_USER" /> 
        <security:intercept-url pattern="/useraccounts/**" access="ROLE_USER" /> 
        <security:intercept-url pattern="/cart/**.html" access="ROLE_USER" /> 
        <security:intercept-url pattern="/ticket/**" access="ROLE_USER,ROLE_BACK_USER" /> 
        <security:intercept-url pattern="/order/**" access="ROLE_USER" /> 
        <security:intercept-url pattern="/comment/**" access="ROLE_USER" /> 
        <security:intercept-url pattern="/personal/**" access="ROLE_USER" /> 
        <security:intercept-url pattern="/favorite/**" access="ROLE_USER" /> 
     
        //需要替换的Filter顺序,配置自定义custom-filter时必须蔣auto-config="false",不然会报已经存在同样的过滤器错误 
        <security:custom-filter ref="myLoginFilter"  position="FORM_LOGIN_FILTER" /> 
        //登出配置 
        <security:logout logout-success-url="${local.service.url}"/> 
    </security:http> 
 
     //密码加密工具类 
    <bean id="encoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"/> 
    //认证管理器 
    <security:authentication-manager alias="authenticationManager"> 
        //UserDetailsService实现 主要用于用户的查询 
        <security:authentication-provider user-service-ref="userLoginService"> 
            <security:password-encoder  ref="encoder"> 
            </security:password-encoder> 
        </security:authentication-provider> 
    </security:authentication-manager> 
 
    <bean id="myLoginFilter" class="com.sale114.www.sercurity.MyUsernamePasswordAuthenticationFilter"> 
        <property name="authenticationManager" ref="authenticationManager"/> 
        <property name="authenticationFailureHandler" ref="failureHandler"/> 
        <property name="authenticationSuccessHandler" ref="successHandler"/> 
    </bean> 
 
    //成功登录后 
    <bean id="successHandler" class="com.sale114.www.sercurity.MySavedRequestAwareAuthenticationSuccessHandler"> 
        <property name="defaultTargetUrl" value="${local.service.url}"/> 
    </bean> 
    //登录失败 
    <bean id="failureHandler" class="com.sale114.www.sercurity.MySimpleUrlAuthenticationFailureHandler"> 
        <property name="defaultFailureUrl" value="${local.service.url}/login.html?validated=false"/> 
    </bean> 
     
    <bean id="authenticationEntryPoint" 
        class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> 
        <property name="loginFormUrl" value="${local.service.url}/login.html" /> 
    </bean> 
</beans> 
 
 
2 UserLoginServiceImpl 查询用户实现类 
 
     @Named("userLoginService") 
public class UserLoginServiceImpl  implements UserDetailsService ,LoginService{ 
 
    @Inject 
    private UserLoginDAO userLoginDAO; 
     
    @Override 
    public WrappedUserLogin getUserLogin() { 
        try { 
            WrappedUserLogin wrappedUserLogin = (WrappedUserLogin) SecurityContextHolder 
                    .getContext().getAuthentication().getPrincipal(); 
            return wrappedUserLogin; 
        } catch (Exception e) { 
            return null; 
        } 
    } 
 
    @Override 
    public UserDetails loadUserByUsername(String username) 
            throws UsernameNotFoundException { 
        System.out.println("用户名-------------"+username); 
        UserLogin userLogin =  null; 
        if(username != null && !"".equals(username)&& username.indexOf("@") > 0){ 
              userLogin = userLoginDAO.findByEmail(username); 
              username = userLogin.getNick(); 
        }else{ 
            userLogin = userLoginDAO.findByNick(username); 
        } 
        System.out.println("user is null ---"+userLogin.getUserType()); 
        String nick = userLogin.getNick(); 
        String email = userLogin.getEmail(); 
        String mobile = userLogin.getMobile(); 
        int userType = userLogin.getUserType(); 
        List<GrantedAuthority> resultAuths = new ArrayList<GrantedAuthority>(); 
         
 
        // 前台用户 
        if (userType == 1) { 
            resultAuths.add(new SimpleGrantedAuthority("ROLE_USER")); 
        } else { 
            resultAuths.add(new SimpleGrantedAuthority("ROLE_BACK_USER")); 
        } 
         
        return new WrappedUserLogin(userLogin.getId(), email, nick, mobile, userLogin.getPassword(), userType,resultAuths); 
    } 
 

 
3 重写用户名密码验证 
     public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{ 
        //用户名 
        public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "j_username"; 
        //密码 
        public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "j_password"; 
        //需要回调的URL 自定义参数 
        public static final String SPRING_SECURITY_FORM_REDERICT_KEY = "spring-security-redirect"; 
         
        /** 
         * @deprecated If you want to retain the username, cache it in a customized {@code AuthenticationFailureHandler} 
         */ 
        @Deprecated 
        public static final String SPRING_SECURITY_LAST_USERNAME_KEY = "SPRING_SECURITY_LAST_USERNAME"; 
 
        private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY; 
        private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY; 
        private String redirectParameter = SPRING_SECURITY_FORM_REDERICT_KEY; 
        private boolean postOnly = true; 
 
        //~ Constructors =================================================================================================== 
 
        public MyUsernamePasswordAuthenticationFilter() { 
           super(); 
        } 
 
        //~ Methods ======================================================================================================== 
 
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { 
            if (postOnly && !request.getMethod().equals("POST")) { 
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); 
            } 
            String username = obtainUsername(request); 
            String password = obtainPassword(request); 
            String redirectUrl = obtainRedercitUrl(request); 
            if (username == null) { 
                username = ""; 
            } 
 
            if (password == null) { 
                password = ""; 
            } 
            //自定义回调URL,若存在则放入Session 
            if(redirectUrl != null && !"".equals(redirectUrl)){ 
                request.getSession().setAttribute("callCustomRediretUrl", redirectUrl); 
            } 
            username = username.trim(); 
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); 
            // Allow subclasses to set the "details" property 
            setDetails(request, authRequest); 
            return this.getAuthenticationManager().authenticate(authRequest); 
        } 
 
        /**
         * Enables subclasses to override the composition of the password, such as by including additional values
         * and a separator.<p>This might be used for example if a postcode/zipcode was required in addition to the
         * password. A delimiter such as a pipe (|) should be used to separate the password and extended value(s). The
         * <code>AuthenticationDao</code> will need to generate the expected password in a corresponding manner.</p>
         *
         * @param request so that request attributes can be retrieved
         *
         * @return the password that will be presented in the <code>Authentication</code> request token to the
         *         <code>AuthenticationManager</code>
         */ 
        protected String obtainPassword(HttpServletRequest request) { 
            return request.getParameter(passwordParameter); 
        } 
 
        /**
         * Enables subclasses to override the composition of the username, such as by including additional values
         * and a separator.
         *
         * @param request so that request attributes can be retrieved
         *
         * @return the username that will be presented in the <code>Authentication</code> request token to the
         *         <code>AuthenticationManager</code>
         */ 
        protected String obtainUsername(HttpServletRequest request) { 
            return request.getParameter(usernameParameter); 
        } 
         
         
        protected String obtainRedercitUrl(HttpServletRequest request) { 
            return request.getParameter(redirectParameter); 
        } 
 
        /**
         * Provided so that subclasses may configure what is put into the authentication request's details
         * property.
         *
         * @param request that an authentication request is being created for
         * @param authRequest the authentication request object that should have its details set
         */ 
        protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { 
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); 
        } 
 
        /**
         * Sets the parameter name which will be used to obtain the username from the login request.
         *
         * @param usernameParameter the parameter name. Defaults to "j_username".
         */ 
        public void setUsernameParameter(String usernameParameter) { 
            Assert.hasText(usernameParameter, "Username parameter must not be empty or null"); 
            this.usernameParameter = usernameParameter; 
        } 
 
        /**
         * Sets the parameter name which will be used to obtain the password from the login request..
         *
         * @param passwordParameter the parameter name. Defaults to "j_password".
         */ 
        public void setPasswordParameter(String passwordParameter) { 
            Assert.hasText(passwordParameter, "Password parameter must not be empty or null"); 
            this.passwordParameter = passwordParameter; 
        } 
 
        /**
         * Defines whether only HTTP POST requests will be allowed by this filter.
         * If set to true, and an authentication request is received which is not a POST request, an exception will
         * be raised immediately and authentication will not be attempted. The <tt>unsuccessfulAuthentication()</tt> method
         * will be called as if handling a failed authentication.
         * <p>
         * Defaults to <tt>true</tt> but may be overridden by subclasses.
         */ 
        public void setPostOnly(boolean postOnly) { 
            this.postOnly = postOnly; 
        } 
 
     

 
 
 
4 SimpleUrlAuthenticationSuccessHandler重写 
     public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{ 
     @Value(value = "${local.service.url}") 
     private String LOCAL_SERVER_URL; 
     
     protected final Log logger = LogFactory.getLog(this.getClass()); 
 
        private RequestCache requestCache = new HttpSessionRequestCache(); 
 
        @Override 
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, 
                Authentication authentication) throws ServletException, IOException { 
            SavedRequest savedRequest = requestCache.getRequest(request, response); 
            if (savedRequest == null) { 
                System.out.println("savedRequest is null "); 
                //用户判断是否要使用上次通过session里缓存的回调URL地址 
                int flag = 0; 
                //通过提交登录请求传递需要回调的URL callCustomRediretUrl 
                if(request.getSession().getAttribute("callCustomRediretUrl") != null && !"".equals(request.getSession().getAttribute("callCustomRediretUrl"))){ 
                    String url = String.valueOf(request.getSession().getAttribute("callCustomRediretUrl")); 
                    //若session 存在则需要使用自定义回调的URL 而不是缓存的URL 
                    super.setDefaultTargetUrl(url); 
                    super.setAlwaysUseDefaultTargetUrl(true); 
                    flag = 1; 
                    request.getSession().setAttribute("callCustomRediretUrl", ""); 
                } 
                //重设置默认URL为主页地址 
                if(flag  == 0){ 
                    super.setDefaultTargetUrl(LOCAL_SERVER_URL); 
                } 
                super.onAuthenticationSuccess(request, response, authentication); 
                
                return; 
            } 
            //targetUrlParameter 是否存在 
            String targetUrlParameter = getTargetUrlParameter(); 
            if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) { 
                requestCache.removeRequest(request, response); 
                super.setAlwaysUseDefaultTargetUrl(false); 
                super.setDefaultTargetUrl("/"); 
                super.onAuthenticationSuccess(request, response, authentication); 
                return; 
            } 
            //清除属性 
            clearAuthenticationAttributes(request); 
            // Use the DefaultSavedRequest URL 
            String targetUrl = savedRequest.getRedirectUrl(); 
            logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl); 
            if(targetUrl != null && "".equals(targetUrl)){ 
                targetUrl = LOCAL_SERVER_URL; 
            } 
            getRedirectStrategy().sendRedirect(request, response, targetUrl); 
        } 
 
        public void setRequestCache(RequestCache requestCache) { 
            this.requestCache = requestCache; 
        } 

 
5 认证失败控制类重写 
/**
* <tt>AuthenticationFailureHandler</tt> which performs a redirect to the value of the {@link #setDefaultFailureUrl
* defaultFailureUrl} property when the <tt>onAuthenticationFailure</tt> method is called.
* If the property has not been set it will send a 401 response to the client, with the error message from the
* <tt>AuthenticationException</tt> which caused the failure.
* <p>
* If the {@code useForward} property is set, a {@code RequestDispatcher.forward} call will be made to
* the destination instead of a redirect.
*
* @author Luke Taylor
* @since 3.0
*/ 
public class MySimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler{ 
 
    protected final Log logger = LogFactory.getLog(getClass()); 
 
    private String defaultFailureUrl; 
    private boolean forwardToDestination = false; 
    private boolean allowSessionCreation = true; 
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); 
    @Value(value = "${local.service.url}") 
    private String LOCAL_SERVER_URL; 
     
    public MySimpleUrlAuthenticationFailureHandler() { 
    } 
 
    public MySimpleUrlAuthenticationFailureHandler(String defaultFailureUrl) { 
        setDefaultFailureUrl(defaultFailureUrl); 
    } 
 
    /**
     * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise returns a 401 error code.
     * <p>
     * If redirecting or forwarding, {@code saveException} will be called to cache the exception for use in
     * the target view.
     */ 
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, 
            AuthenticationException exception) throws IOException, ServletException { 
        //认证失败区别前后台:LOGIN URL 
        if(request.getParameter("spring-security-redirect") != null){ 
              request.getSession().setAttribute("callUrlFailure", request.getParameter("spring-security-redirect")); 
        } 
        //若有loginUrl 则重定向到后台登录界面 
        if(request.getParameter("loginUrl") != null && !"".equals(request.getParameter("loginUrl"))){ 
            defaultFailureUrl = LOCAL_SERVER_URL+"/backlogin.html?validated=false"; 
        } 
        //defaultFailureUrl 默认的认证失败回调URL 
        if (defaultFailureUrl == null) { 
            logger.debug("No failure URL set, sending 401 Unauthorized error"); 
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage()); 
        } else { 
            saveException(request, exception); 
            if (forwardToDestination) { 
                logger.debug("Forwarding to " + defaultFailureUrl); 
                request.getRequestDispatcher(defaultFailureUrl).forward(request, response); 
            } else { 
                logger.debug("Redirecting to " + defaultFailureUrl); 
                redirectStrategy.sendRedirect(request, response, defaultFailureUrl); 
            } 
        } 
    } 
 
    /**
     * Caches the {@code AuthenticationException} for use in view rendering.
     * <p>
     * If {@code forwardToDestination} is set to true, request scope will be used, otherwise it will attempt to store
     * the exception in the session. If there is no session and {@code allowSessionCreation} is {@code true} a session
     * will be created. Otherwise the exception will not be stored.
     */ 
    protected final void saveException(HttpServletRequest request, AuthenticationException exception) { 
        if (forwardToDestination) { 
            request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); 
        } else { 
            HttpSession session = request.getSession(false); 
 
            if (session != null || allowSessionCreation) { 
                request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); 
            } 
        } 
    } 
 
    /**
     * The URL which will be used as the failure destination.
     *
     * @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp".
     */ 
    public void setDefaultFailureUrl(String defaultFailureUrl) { 
        this.defaultFailureUrl = defaultFailureUrl; 
    } 
 
    protected boolean isUseForward() { 
        return forwardToDestination; 
    } 
 
    /**
     * If set to <tt>true</tt>, performs a forward to the failure destination URL instead of a redirect. Defaults to
     * <tt>false</tt>.
     */ 
    public void setUseForward(boolean forwardToDestination) { 
        this.forwardToDestination = forwardToDestination; 
    } 
 
    /**
     * Allows overriding of the behaviour when redirecting to a target URL.
     */ 
    public void setRedirectStrategy(RedirectStrategy redirectStrategy) { 
        this.redirectStrategy = redirectStrategy; 
    } 
 
    protected RedirectStrategy getRedirectStrategy() { 
        return redirectStrategy; 
    } 
 
    protected boolean isAllowSessionCreation() { 
        return allowSessionCreation; 
    } 
 
    public void setAllowSessionCreation(boolean allowSessionCreation) { 
        this.allowSessionCreation = allowSessionCreation; 
    } 
 

 
     6 登录Controller和页面省略 
分享到:
评论

相关推荐

    Spring Security自定义登录原理及实现详解

    在本文中,我们将深入探讨Spring Security的自定义登录原理和实现,这对于理解和构建安全的Web应用程序至关重要。Spring Security是一个强大的安全框架,提供了丰富的功能来保护我们的应用程序,包括用户认证、授权...

    SpringSecurity素材.rar

    6. **自定义登录逻辑**:可能包括如何处理登录失败和成功后的回调,以及自定义登录表单的行为。 7. **记住我功能**:讨论如何实现“记住我”功能,允许用户在关闭浏览器后一段时间内仍能保持登录状态。 8. **错误...

    spring security oauth2.0 (讲义+代码)

    最后,课程可能还会涵盖Spring Security与Spring Boot的集成,以及如何与JWT(JSON Web Tokens)结合,以实现轻量级的令牌验证。 总而言之,通过学习Spring Security OAuth2.0,开发者能够掌握一套完整的认证授权...

    Spring Security 3 与 CAS单点登录配置-Server

    标题 "Spring Security 3 与 CAS 单点登录配置 - Server" 涉及到的是在企业级应用中实现安全访问控制的重要技术。Spring Security 是一个强大的和高度可定制的安全框架,用于保护基于 Java 的 Web 应用程序。而 CAS...

    SpringSecurity企业及认证全套开发资源.docx

    无论是源码解读、拦截器链分析,还是第三方登录集成、短信验证与登录,甚至是自定义验证授权设计模式,Spring Security都能满足不同场景下的需求。对于希望深入了解Spring Security的企业开发者而言,这份资源文档将...

    Spring_Security入门demo(maven项目)

    你可以自定义这些行为,比如改变登录表单的URL,或者添加注销成功后的回调。 **7. 权限控制** Spring Security支持基于角色的权限控制(RBAC),可以使用`hasRole()`或`hasAnyRole()`来指定需要的角色。此外,还有...

    springsecurity_project

    此外,可能还包括了对登录失败和成功后的回调处理,以及如何实现“记住我”功能。 项目中的"project"文件很可能包含了完整的源代码,包括SpringSecurity的配置文件(如security.xml或WebSecurityConfigurerAdapter...

    springsecurity.pdf

    配置JAAS认证提供者涉及到创建回调处理器和权限授予器等步骤,以便实现与JAAS框架的集成。 #### 八、SiteMinder认证机制 ##### 9.1 概览 SiteMinder认证机制是一种与第三方安全解决方案集成的方式,适用于大型...

    spring-security-oauth2-authorization-server.zip

    5. **定义客户端**:在应用程序配置中,注册OAuth2客户端,包括客户端ID、秘密、授权类型、回调URL和允许的范围。 6. **实现UserDetailsService**:提供用户认证逻辑,例如从数据库加载用户信息。 7. **安全配置**...

    spring-security-demo.zip

    - 对于Web Hook回调的安全保护,可以设置特定的访问规则,确保只有预期的来源才能触发回调。 在"spring-security-demo.zip"的项目中,开发者可能会展示如何配置以上各种功能,通过代码和配置文件来解释如何在实际...

    Jeecg配置单点登录 登录验证完整代码

    这通常通过在CAS管理界面或通过API完成,服务URL指向Jeecg的登录回调地址。 3. **集成CAS客户端库**:在Jeecg项目中,你需要引入CAS客户端库,如`spring-security-cas`,这是一个Spring Security扩展,用于支持CAS...

    SpringBoot+security+pac4j

    这通常涉及配置客户端类型(如OAuth、CAS等)、服务器地址和回调URL。 3. **定义安全规则** 在配置类中,使用`http.authorizeRequests()`方法来定义哪些URL需要授权,哪些可以匿名访问。你可以根据路径、HTTP方法...

    JAAs验证机制.doc

    JaasAuthenticationProvider是Spring Security中处理JAAS认证请求的组件,其配置主要包括登录配置文件路径、登录上下文名称、回调处理器和权限授予器。在给定的示例中,`JaasAuthenticationProvider` 被配置为使用 `...

    2021-01-26-SpringSecurity-OAUTH2-密码模式获取token-源码包hrm-itsource.rar

    整个流程中,Spring Security通过一系列的回调和接口调用,确保了安全性,并且实现了OAuth2的密码模式。理解这个过程对于开发和调试OAuth2授权服务至关重要,因为这有助于我们更好地定制和优化安全设置。 在实际...

    sso单点登录代码.zip

    2. 用户输入凭证后,认证服务器验证成功,生成授权码并重定向回应用A的回调地址,同时将授权码附带在URL参数中。 3. 应用A接收到授权码后,向认证服务器发送请求,换取访问令牌(Access Token)和刷新令牌(Refresh ...

    微信企业号OAuth2验证接口的2种实例(使用SpringMVC)

    总结,微信企业号OAuth2验证接口的实现主要涉及客户端配置、授权回调处理、用户信息获取以及会话管理。SpringMVC提供了便捷的注解支持和自定义过滤器/拦截器机制,使得开发者能灵活地集成和实现OAuth2认证流程。在...

    SpringSecurity2BasicAuthDemo

    可以自定义登录表单,通过设置 `formLogin()` 方法中的回调方法来处理登录请求。登出可以通过调用 `logout()` 方法配置,清除用户的会话信息。 6. **异常处理**:Spring Security 会自动处理未授权和未认证的异常,...

    Springboot+Redis单点登录.zip

    5. 配置回调 URL,处理 SP 返回的服务票验证结果。 6. 编写测试用例,确保 SSO 功能正常工作。 通过以上步骤,我们可以利用 Spring Boot 和 Redis 构建一个高效的 SSO 系统。这种方法不仅简化了用户登录流程,提高...

    demo-oauth2-login:使用Spring Boot 2进行演示OAuth2OIDC登录Spring Security 5

    **OAuth2 和 OpenID Connect (OIDC) 概述** ...通过运行这个示例项目,你可以了解 OAuth2 和 OIDC 在实际应用中的工作原理,并学习如何将它们与 Spring Security 结合使用,为你的应用提供安全、便捷的登录体验。

Global site tag (gtag.js) - Google Analytics