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>

 

 

 

 

 

spring security 学习文档的更多相关文章

  1. 0x02 Spring Cloud 学习文档

    每个Spring项目都有自己的; 它详细解释了如何使用项目功能以及使用它们可以实现的功能. Spring Cloud 版本 参考文档 API文档 Finchley SR2 CURRENT GA Ref ...

  2. spring security 学习一

    1.配置基本的springboot web项目,加入security5依赖,启动项目 浏览器访问,即可出现一个默认的登录页面 2.什么都没有配置 登录页面哪里来的 一般不知从何入手,就看官方文档里是如 ...

  3. [转]Spring Security学习总结一

    [总结-含源码]Spring Security学习总结一(补命名空间配置) Posted on 2008-08-20 10:25 tangtb 阅读(43111) 评论(27)  编辑  收藏 所属分 ...

  4. spring security 学习资料

    spring security 学习资料 网址 Spring Security 文档参考手册中文版 https://springcloud.cc/spring-security.html

  5. SpringBoot + Spring Security 学习笔记(五)实现短信验证码+登录功能

    在 Spring Security 中基于表单的认证模式,默认就是密码帐号登录认证,那么对于短信验证码+登录的方式,Spring Security 没有现成的接口可以使用,所以需要自己的封装一个类似的 ...

  6. 集成 Spring Doc 接口文档和 knife4j-SpringBoot 2.7.2 实战基础

    优雅哥 SpringBoot 2.7.2 实战基础 - 04 -集成 Spring Doc 接口文档和 knife4j 前面已经集成 MyBatis Plus.Druid 数据源,开发了 5 个接口. ...

  7. Openstack api 学习文档 & restclient使用文档

    Openstack api 学习文档 & restclient使用文档 转载请注明http://www.cnblogs.com/juandx/p/4943409.html 这篇文档总结一下我初 ...

  8. 2013 最新的 play web framework 版本 1.2.3 框架学习文档整理

    Play framework框架学习文档 Play framework框架学习文档 1 一.什么是Playframework 3 二.playframework框架的优点 4 三.Play Frame ...

  9. Openstack python api 学习文档 api创建虚拟机

    Openstack python api 学习文档 转载请注明http://www.cnblogs.com/juandx/p/4953191.html 因为需要学习使用api接口调用openstack ...

随机推荐

  1. ubuntu18.04虚拟机突然不能上网问题解决办法

    周末在家啃书学docker,win10上装的虚拟机,ubuntu18.04,突然执行apt-get update报错,域名无法解析,怀疑是dns文件有问题,折腾了很久,各种百度,修改dns文件,仍然报 ...

  2. Effective C++:条款23:宁以non-member、non-friend替换member函数

    (一) 有个class来表示网页浏览器: class WebBrowser { public: void clearChache(); void clearHistory(); void remove ...

  3. 详解SID之终结篇

    今天测试某款监控软件时遇到一个比较棘手的问题,这款软件需要在被监控端安装客户端程序.成功在第一个节点安装好客户端后问题出现了,在其他节点安装时报错无法安装.软件报的错误信息无从下手且系统日志也看不出什 ...

  4. tomcat源码阅读之session管理器(Manager)

    一.UML图分析: (一) Session: Session保存了一个客户端访问服务器时,服务器专门为这个客户端建立一个session用来保存相关的会话信息,session有一个有效时间,这个时间默认 ...

  5. SVN同步

    SVN同步:1.在备份服务器上安装SVN,之后创建同名的库名2.在备机的Repositories的库文件夹下的hooks目录下,备份并修改pre-revprop-change.tmpl文件为pre-r ...

  6. Linux中CPU亲和性(go)

    http://www.cnblogs.com/LubinLew/p/cpu_affinity.html

  7. box-shadow 边框样式

    如下 box-shadow: 0 1px 3px 0 rgba(0,0,0,.2), 0 1px 1px 0 rgba(0,0,0,.14), 0 2px 1px -1px rgba(0,0,0,.1 ...

  8. C#操作VFP的dbf数据库文件实例

    C#操作VFP的dbf数据库文件实例 新一篇: js获取网站跟路径 实例中分别使用Oledb和Odbc操作vfp数据库dbf文件,操作包括:读取,增删改. 已测试可直接使用,使用方法:下面代码分两个部 ...

  9. TextBox(只允许输入字母或者数字)——重写控件

    实现如下: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System ...

  10. 微信JSSDK分享朋友圈微信自定义分享接口

    服务项目 新手技术咨询 企业技术咨询 定制开发 服务说明 QQ有问必答 QQ.微信.电话 微信开发.php开发,网站开发,系统定制,小程序开发 价格说明 200元/月 1000/月 商议       ...