spring security 学习文档

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. @Override
  16. public void
    onAuthenticationSuccess(HttpServletRequest request,
    HttpServletResponse response,
  17. Authentication authentication) throws
    IOException, ServletException {
  18. //
    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. }

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>

 

 

 

 

 

原文地址:https://www.cnblogs.com/lshan/p/9000235.html

时间: 2024-08-26 00:02:59

spring security 学习文档的相关文章

[转]Spring Security学习总结一

[总结-含源码]Spring Security学习总结一(补命名空间配置) Posted on 2008-08-20 10:25 tangtb 阅读(43111) 评论(27)  编辑  收藏 所属分类: Spring .Spring Security Spring Security学习总结一 在认识Spring Security之前,所有的权限验证逻辑都混杂在业务逻辑中,用户的每个操作以前可能都需要对用户是否有进行该项 操作的权限进行判断,来达到认证授权的目的.类似这样的权限验证逻辑代码被分散

Mybatis学习文档

Mybatis学习文档 Mybatis是持久层框架类似于Hibernate的orm持久层框架 1.JDBC访问数据库存在的问题 频繁创建和打开.关闭数据链接,太消耗资源 Sql语句存在硬编码,不利于维护 Sql参数设置硬编码,不利于维护 结果集获取与遍历复杂,存在硬编码,不利于维护,期望查询后返回一个java对象 2.Mybatis介绍 前身是apache下的开源项目,2010有aspache software foundation 迁移到了google code ,并且改名为Mybatis,2

myeclipse中关联spring doc帮助文档

这是一篇分享技巧的文章:使用myeclipse关联帮助文档 ① 选中spring.jar ② 鼠标右击,选择properties,弹出框中选择Javadoc Location,找到对应的文档位置,OK ③ 选择spring.jar中的类 ④ 按住F1,弹出一个help框,选择Java help:Javadoc for 'xxx' ⑤ 下图就是对应的文档内容 myeclipse中关联spring doc帮助文档,码迷,mamicode.com

mfc学习---文档视图架构

MFC的AppWizard可以生成三种类型的应用程序:基于对话框的应用.单文档应用(SDI)和多文档应用(MDI). 一般情况下,采用文档/视结构的应用程序至少应由以下对象组成:       1.应用程序是一个CwinApp派生对象,它充当全部应用程序的容器.应用程序沿消息映射网络分配消息给它的所有子程序.       2.框架窗口是一CfrmeWnd派生对象.       3.文档是一个CDocument派生对象,它存储应用程序的数据,并把这些信息提供给应用程序的其余部分.       4.视

NodeJS-001-Nodejs学习文档整理(转-出自http://www.cnblogs.com/xucheng)

Nodejs学习文档整理 http://www.cnblogs.com/xucheng/p/3988835.html 1.nodejs是什么: nodejs是一个是javascript能在后台运行的平台,具体来时只是使code javascript能在后台运行,因为不在浏览器中运行所以不涉及到document等对象.(Mozilla 则指出 JavaScript 由Core JavaScript 和 Client JavaScript 组成.) 2.nodejs如何运行javascript: n

[转]Spring Security学习总结二

原文链接: http://www.blogjava.net/redhatlinux/archive/2008/08/20/223148.html http://www.blogjava.net/redhatlinux/archive/2008/09/01/226010.html [总结-含源码]Spring Security学习总结二 Posted on 2008-09-01 10:08 tangtb 阅读(9518) 评论(12)  编辑  收藏 所属分类: Spring .Spring Se

Openstack python api 学习文档

Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack,所以上一篇写了一些使用openstack的纯api调用的方法, 但是openstack还提供了更好的python的api,只需要python的包即可,感觉更好使用. 对于compute的api,包是放在了/usr/lib/python2.7/site-packages/novaclient/目录,

Activit最入门学习文档,从如何创建项目开始共20章,看完,任何Java项目集成无压力

Activit流程引擎 本人水平,刚自学java一个多月,然后看视频做的笔记,全部傻瓜式截图教程,反正我学习之前没在网上搜索到任何小白教程, Activit官方的教程真心看不懂,因为都是文字 没具体创建步奏,所以对新手来说很无奈, 然后吧,就把自己的学习经验贡献出来啦 最小白的文档,看完之后,集成到任何java项目中都无压力,我最后的是做了个Jfinal集成,估计这是网上搜到最全的容易懂的入门学习文档,本人自学java一个月,反正我看官方例子什么的都看不懂,然后各搜素也没收到教程视频,还好有别人

solr学习文档之高亮

在<solr学习文档之添加分词词库>一文中,我们学习了如何对一个词组进行分词提取,这一章我们将会使用到分词词库,并介绍如何进行高亮展现 在此之前,我们先了解一下高亮的几个参数 hl:是否开启高亮组件,true为开启,false为不开启 hl.fl:需要开启的高亮字段,多个可用逗号隔开 hl.simple.pre:高亮字段前缀 hl.simple.post:高亮字段后缀 (其他的暂不介绍,想知道的可自行百度) 想要进行高亮站下,需要在schema.xml中将你的字段名(如topicContent