web service

Prepared by:   Sea                                                                                                                                                            29 April, 2018

Contents

1.             The description of springsecurity. 2

1.1.               What is spring security?. 2

1.2.               History. 3

1.3.               Spring Security New characteristics  新特性... 4

1.4.               Why user  springsecurity?. 5

2.             filterchain  filtres. 6

2.1.               Authentication  process. 8

3.             Authentication and authorization--Login example. 10

3.1.               dependencies. 10

3.2.               Login  form... 10

3.3.               Create a class  implements  UserDetailsService. 11

3.4.               Spring security config. 11

3.5.               authentication-success && fail  handler 12

28.1.             validate  CODE.. 13

28.2.             Remeberme function. 16

 

 









1.  The description of springsecurity

1.1.    What is spring security?

Spring Security provides comprehensive security services for Java EE-based enterprise software applications. There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading Java EE solution for enterprise software development. If you’re not using Spring for developing enterprise applications, we warmly encourage you to take a closer look at it. Some familiarity with Spring - and in particular dependency injection principles - will help you get up to speed with Spring Security more easily.

People use Spring Security for many reasons, but most are drawn to the project after finding the security features of Java EE’s Servlet Specification or EJB Specification lack the depth required for typical enterprise application scenarios. Whilst mentioning these standards, it’s important to recognise that they are not portable at a WAR or EAR level. Therefore, if you switch server environments, it is typically a lot of work to reconfigure your application’s security in the new target environment. Using Spring Security overcomes these problems, and also brings you dozens of other useful, customisable security features.

As you probably know two major areas of application security are "authentication" and "authorization" (or "access-control"). These are the two main areas that Spring Security targets. "Authentication" is the process of establishing a principal is who they claim to be (a "principal" generally means a user, device or some other system which can perform an action in your application)."Authorization" refers to the process of deciding whether a principal is allowed to perform an action within your application. To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process. These concepts are common, and not at all specific to Spring Security.

At an authentication level, Spring Security supports a wide range of authentication models. Most of these authentication models are either provided by third parties, or are developed by relevant standards bodies such as the Internet Engineering Task Force. In addition, Spring Security provides its own set of authentication features. Specifically, Spring Se        curity currently supports authentication integration with all of these technologies:

  • HTTP BASIC authentication headers (an IETF RFC-based standard)
  • HTTP Digest authentication headers (an IETF RFC-based standard)
  • HTTP X.509 client certificate exchange (an IETF RFC-based standard)
  • LDAP (a very common approach to cross-platform authentication needs, especially in large environments)
  • Form-based authentication (for simple user interface needs)
  • OpenID authentication
  • Authentication based on pre-established request headers (such as Computer Associates Siteminder)
  • Jasig Central Authentication Service (otherwise known as CAS, which is a popular open source single sign-on system)
  • Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol)
  • Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time)
  • Anonymous authentication (allowing every unauthenticated call to automatically assume a particular security identity)
  • Run-as authentication (which is useful if one call should proceed with a different security identity)
  • Java Authentication and Authorization Service (JAAS)
  • Java EE container authentication (so you can still use Container Managed Authentication if desired)
  • Kerberos
  • Java Open Source Single Sign-On (JOSSO) *
  • OpenNMS Network Management Platform *
  • AppFuse *
  • AndroMDA *
  • Mule ESB *
  • Direct Web Request (DWR) *
  • Grails *
  • Tapestry *
  • JTrac *
  • Jasypt *
  • Roller *
  • Elastic Path *
  • Atlassian Crowd *
  • Your own authentication systems (see below)

(* Denotes provided by a third party

Many independent software vendors (ISVs) adopt Spring Security because of this significant choice of flexible authentication models. Doing so allows them to quickly integrate their solutions with whatever their end clients need, without undertaking a lot of engineering or requiring the client to change their environment. If none of the above authentication mechanisms suit your needs, Spring Security is an open platform and it is quite simple to write your own authentication mechanism. Many corporate users of Spring Security need to integrate with "legacy" systems that don’t follow any particular security standards, and Spring Security is happy to "play nicely" with such systems.

Irrespective of the authentication mechanism, Spring Security provides a deep set of authorization capabilities. There are three main areas of interest: authorizing web requests, authorizing whether methods can be invoked and authorizing access to individual domain object instances. To help you understand the differences, consider the authorization capabilities found in the Servlet Specification web pattern security, EJB Container Managed Security and file system security respectively. Spring Security provides deep capabilities in all of these important areas, which we’ll explore later in this reference guide.

 

 

 

 

1.2.    History 

Spring Security began in late 2003 as "The Acegi Security System for Spring". A question was posed on the Spring Developers' mailing list asking whether there had been any consideration given to a Spring-based security implementation. At the time the Spring community was relatively small (especially compared with the size today!), and indeed Spring itself had only existed as a SourceForge project from early 2003. The response to the question was that it was a worthwhile area, although a lack of time currently prevented its exploration.

With that in mind, a simple security implementation was built and not released. A few weeks later another member of the Spring community inquired about security, and at the time this code was offered to them. Several other requests followed, and by January 2004 around twenty people were using the code. These pioneering users were joined by others who suggested a SourceForge project was in order, which was duly established in March 2004.

In those early days, the project didn’t have any of its own authentication modules. Container Managed Security was relied upon for the authentication process, with Acegi Security instead focusing on authorization. This was suitable at first, but as more and more users requested additional container support, the fundamental limitation of container-specific authentication realm interfaces became clear. There was also a related issue of adding new JARs to the container’s classpath, which was a common source of end user confusion and misconfiguration.

Acegi Security-specific authentication services were subsequently introduced. Around a year later, Acegi Security became an official Spring Framework subproject. The 1.0.0 final release was published in May 2006 - after more than two and a half years of active use in numerous production software projects and many hundreds of improvements and community contributions.

Acegi Security became an official Spring Portfolio project towards the end of 2007 and was rebranded as "Spring Security".

Today Spring Security enjoys a strong and active open source community. There are thousands of messages about Spring Security on the support forums. There is an active core of developers who work on the code itself and an active community which also regularly share patches and support their peers.

.

 

1.3.    Spring Security New characteristics  新特性

Spring Security 4.0 release solved  175+  tickets 。

function

 

  The highlights of the new features of Spring Security 4 below::

https://vincentmi.gitbooks.io/spring-security-reference-zh/content/2_whats_new_in_spring_security_4.html

Do more security default values
The role method does not need to include ROLE_, for example, it needs to include the following contents in the XML configuration:
<intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
Now you can choose to ignore the ROLE_ prefix. We do this to eliminate repetition. Specifically, since the hasRole expression has defined a value as a role, it automatically adds a prefix if it does not exist. The following configuration is the same as the previous configuration effect:
<intercept-url pattern="/**" access="hasRole('USER')"/>
Like configuration below
@PreAuthorize("hasRole('ROLE_USER')")
The simpler configuration is the same as below
@PreAuthorize("hasRole('USER')")
  • A lot of integration tests are added to the examples
  • Abandon @EnableWebMvcSecurity - by updating the minimum Spring version, we now use @EnableWebSecurity and MVC integration by default, and still allow it to be overwritten.。

form  3.x to  4.x

Spring Security in response to the development of application vulnerabilities, as a major version, the Spring Security team took the opportunity to make some non passive changes, which is focused on:

• ensure that the default configuration is more secure

• try to avoid information disclosure as far as possible

remove the abandoned API

 

 

1.4.    Why user  springsecurity? 

In the Spring Security world, it is possible to distinguish

which resources can be accessed anonymously, which needs role permissions,

 which pages provide login functions,

how to authenticated users, and how the user's password is encrypted.

Which resources must use the HTTPS protocol, and how the resources correspond to the access ports.

 

In other word:

提供了一套权限框架,这套框架是可行的;

提供了很多用户身份认证功能,可以节约大量开发工作;

提供了角色判断功能

提供了form-login、remember  me等控制。

A framework of permission is provided, which is feasible.

It provides many user authentication functions and can save a lot of development work.

Role judgment is provided

Form-login, remember me and other controls are provided.。

 

Comparison between Shiro and Spring Security: https://blog.csdn.net/liyuejin/article/details/77838868

 

Shiro is easier to use, realize and understand most than Spring.

The only reason why Spring Security is more famous is the brand name.

"Spring" is famous for its simplicity. But ironically, many people find it difficult to install Spring Security.

However, Spring Security has better community support.

Apache Shiro has an additional module in Spring Security processing cryptography.

Spring-security is a good combination of spring, if the springmvc used in the project is very convenient to use. But if there is no spring in the project, don't think about it.

Shiro is powerful, simple and flexible. The project under Apache is more reliable and does not bind to any framework or container. It can run independently.

 

 

 

 

2.  filterchain  filtres

                                                                                                                                                                       http://eryk.iteye.com/blog/626651

1.HttpSessionContextIntegrationFilter

 

Located at the top of the filterchain, the first working filter.

Function:

First, before implementing other filters, it is the first to judge whether a session exists in the user's SecurityContext. If it exists, take the SecurityContext out and put it in SecurityContextHolder for other parts of Spring Security. If it does not exist, create a SecurityContext or put it in SecurityContextHolder for other parts of Spring Security.

Use two, after all filter execution, clear SecurityContextHolder, because SecurityContextHolder is based on ThreadLocal, if the operation is completed after the completion of the ThreadLocal, will be affected by the server thread pool mechanism

 

2.LogoutFilter

 

Handle logout requests only, defaults to /j_spring_security_logout.

 

The purpose is to destroy the user session, empty the SecurityContextHolder, and then redirect it to the successful page when the user sends the cancellation request. It can be combined with mechanisms such as rememberMe to empty user cookie while logoff.

Eg:

    <http pattern="/login/pages/login.html" security="none"></http>

    <http pattern="/403.html" security="none"></http>

   

<http auto-config="true" use-expressions="true"

  

        <logout logout-url="/logout"

                logout-success-url="/"  

                invalidate-session="true" 

                delete-cookies="JSESSIONID"/> 

              

    </http>

 

 

 

 

3.AuthenticationProcessingFilter

 

All the operations related to form landing are handled in the process of filtering form login.

The /j_spring_security_check request is only handled by default, which should be the user's submission address using the form login, and the other parameters required by form can be referred to:

 

The basic operation of this filter is to determine whether the user is valid by the user name and password, and if the login is successful, it jumps to the successful page (the protected page that may be accessed before the login, or the default success page), and if the login fails, it jumps to the failure page.

 

 login-processing-url="/user/login"

 

 

4.DefaultLoginPageGeneratingFilter

 

This filter is used to generate a default login page with the default access address of /spring_security_login. The default login page supports user input username, password, and rememberMe function, but because it is too ugly, it can only be done in the demonstration, and it can not be used directly in the actual project. In the middle.

 

Custom landing page

 

    <http pattern="/login/pages/login.html" security="none"></http>

    <http pattern="/403.html" security="none"></http>

   

    <http auto-config="true" use-expressions="true" >

<!--     <http auto-config="true" use-expressions="true" entry-point-ref="customEnteryPoint"> -->

        <csrf disabled="true" />

          <!-- <intercept-url pattern="/**" access="isAuthenticated()"/> -->

      <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>

     

        <form-login login-page="/index.html"

                 login-processing-url="/user/login"

                   default-target-url="/users/pages/userlist.html"

                   authentication-failure-url="/403.html"

                   always-use-default-target='true'/>

       

       

        <logout logout-url="/logout"

                logout-success-url="/"  

                invalidate-session="true" 

                delete-cookies="JSESSIONID"/> 

               

         <!-- 增加一个filter,, 这个filter位于FILTER_SECURITY_INTERCEPTOR之前   -->

     <custom-filter ref="validateCodeFilter" before="FIRST" />  

    </http>

 

 

5.BasicProcessingFilter

 

This filter is used for basic verification, functions similar to AuthenticationProcessingFilter, but only in different ways of verification.

Add basic authentication, remove auto-config= "true" and add <http-basic / >

 

<http auto-config="true">
    <http-basic />
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
    <intercept-url pattern="/" access="ROLE_USER" />
</http>

 

6.RememberMeProcessingFilter

 

This filter implements the RememberMe function. When the user cookie has the rememberMe tag, the filter automatically implements the user login based on the tag, and creates the SecurityContext to grant the corresponding permissions.

Using auto-config= "true" in the configuration file will automatically enable rememberMe.

In fact, rememberMe in Spring Security depends on cookie, and when users choose to use rememberMe when they log in, the system will generate a unique identity for the user after the login success, and save the identity into cookie, and we can check the cookie in the user's computer through a browser.

 

  1. 7.    AnonymousProcessingFilter

 

In order to ensure the integrity of operation, users can assign anonymous users' permission by default.

Using the auto-config= "true" in the configuration file will enable anonymous login. After enabling anonymous login, if we want to allow access to some resources without logging in, we can proceed with the following configuration.

 

Method:1

<http auto-config='true'>
    <intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY" /> //Or ROLE_ANONYMOUS
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

 

 Method:2

<http auto-config='true'>
    <intercept-url pattern="/" filters="none" />
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

 

Method:3

   <http auto-config='true'>

<http pattern="/login/pages/login.html" security="none"></http>

      <http pattern="/403.html" security="none"></http>

</http>

 

 

8.ExceptionTranslationFilter

 

The function of this filter is to deal with an exception thrown by FilterSecurityInterceptor in the process, then redirect the request to the corresponding page, or return the corresponding response error code.

 

 

9.SessionFixationProtectionFilter

 

Defense session forged attack.

The solution to the problem of session fix is very simple, as long as the user's current session is destroyed and a session can be regenerated after the user's login is successful.。

 

<http auto-config='true' session-fixation-protection="none">   //migrateSession | newSession
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>

 

The value of session-fixation-protection has three choices, none, migrateSession and newSession. The default is migrationSession

10.FilterSecurityInterceptor

 

User authority control is contained in this filter.

 

Function 1: if the user has not landed, the AuthenticationCredentialsNotFoundException "not yet authenticated exception" is thrown.

Function two: if the user is logged in, but does not have access to the current resources, then the AccessDeniedException "deny access exception" is thrown.

Function three: if users are logged in and have access to the current resources, they are released.

 

 

 

 

2.1.    Authentication  process

Authentication   theory

 

Detail process

 

 

 

 

 

       
   
 
   
 
     

 

 

 

//看一下源码流程   

 

3.  Authentication and authorization--Login example 

3.1.    dependencies

 

//<spring-security.version>4.0.2.RELEASE</spring-security.version>

<dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-core</artifactId>

         <version>${spring-security.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-web</artifactId>

            <version>${spring-security.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.social</groupId>

            <artifactId>spring-social-web</artifactId>

            <version>1.1.4.RELEASE</version>

         </dependency>

       <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-config</artifactId>

            <version>${spring-security.version}</version>

        </dependency>

 

3.2.    Login  form

 

 <form class="form-horizontal" method="POST" action="/user/login">

     <div class="form-group">

         <label for="username" class="col-sm-2 control-label">用户名</label>

         <div class="col-sm-6">

             <input type="text" class="form-control" id="username"   name="username" ng-model="user.username"

                    placeholder="请输入用户名!" required>

         </div><span style="color: red">{{message}}</span>

     </div>

     <div class="form-group">

         <label for="password" class="col-sm-2 control-label">密码</label>

         <div class="col-sm-6">

             <input type="password" class="form-control" id="password" name="password" ng-model="user.password"

                    placeholder="请输入密码!" required>

         </div><span style="color: red">{{message1}}</span>

     </div>

    

     <div class="form-group">

         <label for="validateCode" class="col-sm-2 control-label">验证码</label>

         <div class="col-sm-6">

             <input type="text" class="form-control" id="validateCode" name="imageCode"

                    placeholder="请输入验证码!" required>

         </div>

         <div > <img id="loginform_Code" alt="验证码" src="/validate/image"

         onclick="javascript:document.getElementById('loginform_Code').src='/validate/image?'+Math.random();" />

         </div>

        

     </div>

   

     <div class="form-group">

         <div class="col-sm-offset-2 col-sm-10">

            <input type="submit" width="100"  value="登录"

                    style="background: url('../../img/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;">

         </div>

     </div>

 </form>

 

3.3.    Create a class  implements  UserDetailsService

public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired

    private UserRepository  userRepository;

    @Override

    @Transactional(readOnly = true)

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

   //get user from db  and  right

        User user = userRepository.getUserByUsername(username);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();

        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));

        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(), grantedAuthorities);

    }

}

 

3.4.    Spring security config

<?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-3.0.xsd

        http://www.springframework.org/schema/security

        http://www.springframework.org/schema/security/spring-security.xsd">

          

     

    <http pattern="/**/*.css" security="none"></http> 

    <http pattern="/**/*.jpg" security="none"></http> 

    <http pattern="/**/*.jpeg" security="none"></http> 

    <http pattern="/**/*.gif" security="none"></http> 

    <http pattern="/**/*.png" security="none"></http> 

    <http pattern="/**/*.js" security="none"></http> 

<http pattern="/validate/image" security="none"></http> 

 

   

    <http pattern="/index.html" security="none"></http>

    <http pattern="/login/pages/login.html" security="none"></http>

<http pattern="/403.html" security="none"></http>

 

   

    <http auto-config="true" use-expressions="true" >

        <csrf disabled="true" />

          <!-- <intercept-url pattern="/**" access="isAuthenticated()"/> -->

        <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>

     

        <form-login login-page="/index.html"

                 login-processing-url="/user/login"

                  default-target-url='/users/pages/userlist.html'

                  authentication-failure-url="/403.html"

                  always-use-default-target='true'/>

       

       

        <logout logout-url="/logout"

                logout-success-url="/"  

                invalidate-session="true" 

                delete-cookies="JSESSIONID"/> 

               

         <!—add a filter,this  filter before FILTER_SECURITY_INTERCEPTOR-->

     <custom-filter ref="validateCodeFilter" before="FIRST" /> 

    

    </http>

   

    <beans:bean id="validateCodeFilter"  class="com.icil.filter.ValidateCodeFilter"></beans:bean>

  

   

    <authentication-manager alias="authenticationManager">

        <authentication-provider user-service-ref="userDetailsServiceImpl">

          <password-encoder ref="encoder"></password-encoder> 

        </authentication-provider>

</authentication-manager>

 

 

    <beans:bean id="userDetailsServiceImpl" class="com.icil.service.UserDetailsServiceImpl"></beans:bean>

 

   <beans:bean id="encoder"

          class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">

        <beans:constructor-arg name="strength" value="11"/>

    </beans:bean>

 

 

 

 

 

 

 

 

3.5.    authentication-success && fail  handler

  1. package com.icil.securityHandler;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import org.springframework.security.core.Authentication;
  7. import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
  8. import org.springframework.stereotype.Component;
  9. /**
  10.  * AuthenticationSuccessHandler
  11.  * @author Sea
  12.  * */
  13. @Component
  14. public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
  15.  
  16.     @Override
  17.     public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
  18.             Authentication authentication) throws IOException, ServletException {
  19.             // we can get all info from here

               //we can do what we do!

  1.             System.out.println("认证成功!!");
  2.             response.sendRedirect("/users/pages/userlist.html");
  3.     }
  4.  
  5. }
  6.  

 

package com.icil.securityHandler;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;

import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import org.springframework.stereotype.Component;

@Component

public class MyAuthenticationFailureHandler implements  AuthenticationFailureHandler{

         @Override

         public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,

                            AuthenticationException exception) throws IOException, ServletException {

                   // TODO Auto-generated method stub

                   }

 

}

 

28.1. validate  CODE

imageCodeConller

 

@RestController

public class ImageCodeController {

        

         public static final String SESSION_KEY="SESSION_KEY_IMAGE_CODE";

         private SessionStrategy  sessionStrategy=new HttpSessionSessionStrategy() ;

        

         @GetMapping("/validate/image")

         public void  generateImageCode(HttpServletRequest request,HttpServletResponse response) throws IOException{

             // create a  mageCode

                   ImageCode imageCode=creatImageCode(request);

                    /**

                     *  param1:sessionStrategy will get session fron the request

                     */

                sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);

                   ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());

         }

        

                  

private ImageCode creatImageCode(HttpServletRequest request) {

      ImageCodeGenerate imageCodes = new ImageCodeGenerate(120,35,5,150); 

           //30s late code expire

       return new ImageCode(imageCodes.getBuffImg(), imageCodes.getCode(), 30);

         }

                  

}

 

Imagecode

package com.icil.imagecode;

 

import java.awt.image.BufferedImage;

import java.time.LocalDateTime;

 

/**

 * @author sea

 */

public class ImageCode {

           private BufferedImage image;

           private String code;

           private LocalDateTime expireTime;   //s

           public boolean isExpired;

          

         public ImageCode() {

                   super();

         }

 

 

         public ImageCode(BufferedImage image, String code, int expiredinf) {

                   super();

                   this.image = image;

                   this.code = code;

                   this.expireTime = LocalDateTime.now().plusSeconds(expiredinf);

         }

        

         public boolean isExpired(){

                  return LocalDateTime.now().isAfter(expireTime);

         }

         public BufferedImage getImage() {

                   return image;

         }

         public void setImage(BufferedImage image) {

                   this.image = image;

         }

         public String getCode() {

                   return code;

         }

         public void setCode(String code) {

                   this.code = code;

         }

         public LocalDateTime getExpireTime() {

                   return expireTime;

         }

         public void setExpireTime(LocalDateTime expireTime) {

                   this.expireTime = expireTime;

         }

         }

 

ValidateCodeFilter

 

/**

 * extends OncePerRequestFilter  spring提供的,保证过滤器只被调用一次

 * @author lenove

 *

 */

public class ValidateCodeFilter extends OncePerRequestFilter {

 

         private AuthenticationFailureHandler   authenticationFailureHandler ;

         private SessionStrategy sessionStrategy=new HttpSessionSessionStrategy();

         @Override

         protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

                            throws ServletException, IOException {

                                     /*** is login request ?    /user/login   post*/

                            if(StringUtils.equals("/user/login", request.getRequestURI())

                                     &&StringUtils.equalsIgnoreCase("post", request.getMethod())){

                                // is login

                              try {

                                     Validate(new ServletWebRequest(request));

                            } catch (ValidatecodeException e) {

                                     //validate imagecode fail

                                     //authenticationFailureHandler.onAuthenticationFailure(request, response, e);

                                     e.printStackTrace();

                                     response.sendRedirect("/");

                                     return ;

                            }

                   }

                   // continue others  filter

                   filterChain.doFilter(request, response);

         }

  

                 private void Validate(ServletWebRequest request) throws ServletRequestBindingException {

                            ImageCodeimageCodeInSession=(ImageCode)sessionStrategy.getAttribute(request, ImageCodeController.SESSION_KEY);

                   //ServletRequestUtils spring tool

                   String codeInRequestScope = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");

                   if(codeInRequestScope==null){

                            throw new ValidatecodeException("验证码不能为空!");

                   }

                   if(imageCodeInSession.isExpired){

                            sessionStrategy.removeAttribute(request, ImageCodeController.SESSION_KEY);

                            throw new ValidatecodeException("验证码已过期!");

                   }

                   if(!StringUtils.equals(codeInRequestScope, imageCodeInSession.getCode())){

                            sessionStrategy.removeAttribute(request, ImageCodeController.SESSION_KEY);

                            throw new ValidatecodeException("验证码错误!");

                   }

                   sessionStrategy.removeAttribute(request, ImageCodeController.SESSION_KEY);

                            }

         public AuthenticationFailureHandler getAuthenticationFailureHandler() {

                   return authenticationFailureHandler;

         }

         public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {

                   this.authenticationFailureHandler = authenticationFailureHandler;

         }

         public SessionStrategy getSessionStrategy() {

                   return sessionStrategy;

         }

         public void setSessionStrategy(SessionStrategy sessionStrategy) {

                   this.sessionStrategy = sessionStrategy;

         }

}

 

 

 

28.2. Remeberme function

Remeberme  theory

 

 

config

<remember-me token-repository-ref="jdbcTokenRepositoryImpl"

            token-validity-seconds="300" 

            user-service-ref="userDetailsServiceImpl"/>

 

<beans:bean id="jdbcTokenRepositoryImpl" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">

          <beans:property name="dataSource"  ref="dataSource" />

    <!-- <beans:property name="createTableOnStartup"  value="true" /> -->

    </beans:bean>

 

 

 

 

 

posted on 2018-05-06 23:02  lshan  阅读(625)  评论(0编辑  收藏  举报