⒈自定义登录页面

 package cn.coreqi.security.config;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
//http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
//.loginPage("/coreqi-signIn.html") //指定登录页面
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
}
 package cn.coreqi.security.controller;

 import cn.coreqi.security.support.SimpleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @RestController
public class SecurityController { private Logger logger = LoggerFactory.getLogger(getClass()); //拿到引发跳转的请求
private RequestCache requestCache = new HttpSessionRequestCache(); //SpringSecurity执行身份认证跳转之前会将当前的请求缓存到HttpSessionRequestCache中
//我们可以通过HttpSessionRequestCache把之前缓存的请求拿出来。 private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); //Spring用于跳转的工具 /**
* 当需要身份认证时,跳转到这里
* @param request
* @param response
* @return
*/
@GetMapping("/authentication/require")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED) //返回401状态码
public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
SavedRequest savedRequest = requestCache.getRequest(request,response); //SavedRequest就是跳转前的请求
if(savedRequest != null){ //如果请求缓存存在的话
String target = savedRequest.getRedirectUrl(); //拿到引发跳转的请求URL
logger.info("引发跳转的请求URL是:" + target);
if(StringUtils.endsWithIgnoreCase(target,".html")){ //引发跳转的请求URL是否以html结尾
redirectStrategy.sendRedirect(request,response,"/coreqi-signIn.html"); //将请求跳转到指定的Url
}
}
return new SimpleResponse(401,"访问的服务需要身份认证,请引导用户到登陆页面",null);
}
}

⒉自定义登录成功处理

  默认情况下SpringSecurity登录成功了将会跳转到之前引发登录的那个请求上去,如果我们需要自定义登录成功后的处理过程,只需要实现AuthenticationSuccessHandler接口。(SpringSecurity默认的成功处理器是SavedRequestAwareAuthenticationSuccessHandler)

 package cn.coreqi.security.authentication;

 import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @Component("coreqiAuthenticationSuccessHandler")
public class CoreqiAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private ObjectMapper objectMapper; //将对象转换为Json的工具类,SpringMVC在启动的时候会自动为我们注册ObjectMapper
/**
*
* @param httpServletRequest 不知道
* @param httpServletResponse 不知道
* @param authentication Authentication接口是SpringSecurity的一个核心接口,它的作用是封装我们的认证信息,包含认证请求中的一些信息,包括认证请求的ip,Session是什么,以及认证用户的信息等等。
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
logger.info("登录成功"); httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
}
}

配置

 package cn.coreqi.security.config;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private AuthenticationSuccessHandler coreqiAuthenticationSuccessHandler; @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
//http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
//.loginPage("/coreqi-signIn.html") //指定登录页面
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.successHandler(coreqiAuthenticationSuccessHandler) //登录成功以后要用我们自定义的登录成功处理器,不用Spring默认的。
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
}

⒊自定义登录失败处理

只需要实现AuthenticationSuccessHandler接口即可。(默认为SimpleUrlAuthenticationFailureHandler)

 package cn.coreqi.security.authentication;

 import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; @Component("coreqiAuthenticationFailureHandler")
public class CoreqiAuthenticationFailureHandler implements AuthenticationFailureHandler { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private ObjectMapper objectMapper; //将对象转换为Json的工具类,SpringMVC在启动的时候会自动为我们注册ObjectMapper /**
*
* @param httpServletRequest 不知道
* @param httpServletResponse 不知道
* @param e AuthenticationException对象包含了在认证过程中发生的错误产生的异常
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
logger.info("登录失败"); httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); //500状态码
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e));
}
}

配置

 package cn.coreqi.security.config;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; @Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private AuthenticationSuccessHandler coreqiAuthenticationSuccessHandler; @Autowired
private AuthenticationFailureHandler coreqiAuthenticationFailureHandler; @Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
} @Override
protected void configure(HttpSecurity http) throws Exception {
//http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
//.loginPage("/coreqi-signIn.html") //指定登录页面
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.successHandler(coreqiAuthenticationSuccessHandler) //登录成功以后要用我们自定义的登录成功处理器,不用Spring默认的。
.failureHandler(coreqiAuthenticationFailureHandler) //自己体会把
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
}

SpringSecurity个性化用户认证流程的更多相关文章

  1. 阶段5 3.微服务项目【学成在线】_day17 用户认证 Zuul_01-用户认证-用户认证流程分析

    1 用户认证 1.1 用户认证流程分析 用户认证流程如下: 访问下面的资源需要携带身份令牌和jwt令牌,客户端可以通过身份认证的令牌从服务端拿到长令牌, 一会要实现认证服务请求用户中心从数据库内来查询 ...

  2. SpringSecurity自定义用户认证逻辑

    ⒈处理用户信息获取逻辑 用户信息的获取逻辑是被SpringSecurity封装到UserDetailsService接口里面的 package org.springframework.security ...

  3. 02 spring security 自定义用户认证流程

    1. 自定义登录页面 (1)首先在static目录下面创建login.html       注意: springboot项目默认可以访问resources/resources, resources/s ...

  4. Spring Security构建Rest服务-0701-个性化用户认证流程

    上一篇说了用户认证的基本流程,但是上一篇当访问一个受保护的服务后,如果未认证会调到默认的登录页面,这样是不行的,而且认证成功后,就直接访问了那个服务,如果想要做认证成功后做一些操作,还需要自定义. 个 ...

  5. SpringSecurity认证流程详解

    SpringSecurity基本原理 在之前的文章<SpringBoot + Spring Security 基本使用及个性化登录配置>中对SpringSecurity进行了简单的使用介绍 ...

  6. springSecurity + jwt + redis 前后端分离用户认证和授权

    记录一下使用springSecurity搭建用户认证和授权的代码... 技术栈使用springSecurity + redis + JWT + mybatisPlus 部分代码来自:https://b ...

  7. Spring Security教程(八):用户认证流程源码详解

    本篇文章主要围绕下面几个问题来深入源码: 用户认证流程 认证结果如何在多个请求之间共享 获取认证用户信息 一.用户认证流程 上节中提到Spring Security核心就是一系列的过滤器链,当一个请求 ...

  8. REST Framework 的用户认证组件

    用户认证流程: 我们要知道这个流程是怎么走的? 认证之后做的什么? 怎么认证?这三个条件 认证流程:就是使用BaseAuthentication这个模块来做认证,判断你登陆成功传递过来的随机字符串是否 ...

  9. nginx 请求文件 进行用户认证/鉴权: internal(限制为内部调用)

    在进行WEB开发时, 必然会遇到向用户返回文件的场景(如图片, 文档等等), 当返回的文件较小时, 我们可以直接通过接口以数据流的形式向前台返回, 因为文件较小, 因此也不会太过于影响响应速度及服务器 ...

随机推荐

  1. HDFS集群优化篇

    HDFS集群优化篇 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.操作系统级别优化 1>.优化文件系统(推荐使用EXT4和XFS文件系统,相比较而言,更推荐后者,因为XF ...

  2. javaweb简单登陆例子

    JSP+Servlet+JavaBean简单程序例子——用户名密码登陆,摘自<Tomcat&JavaWeb 技术手册>,亲测可用. IDE环境:MyEclipse10 1.建立We ...

  3. Ubuntu修改Apache默认Web端口

    改成你要的端口,默认为80,这里我改成了8080,https改成了444,保存之后寻找000/default.conf并修改成和ports.conf文件一样的http端口,然后重启Apache服务器即 ...

  4. cocos-2dx 3.17 环境搭建 与 新建工程

    由于上次在ubuntu中安装了cocos2dx的时候环境被破坏了,所以本文是基于 Windows 编写的 平台: OS : windows 10 compiler   : VS 2015 下载 coc ...

  5. python爬虫慕课基础1

    test_urllib2.py import http.cookiejar from urllib import request url = "http://www.baidu.com&qu ...

  6. ACM-ICPC 2018 焦作赛区网络预赛 B Mathematical Curse(DP)

    https://nanti.jisuanke.com/t/31711 题意 m个符号必须按顺序全用,n个房间需顺序选择,有个初始值,问最后得到的值最大是多少. 分析 如果要求出最大解,维护最大值是不能 ...

  7. bzoj千题计划321:bzoj5251: [2018多省省队联测]劈配(网络流 + 二分)

    https://www.lydsy.com/JudgeOnline/problem.php?id=5251 第一问: 左边一列点代表学生,右边一列点代表导师 导师向汇点连流量为 人数限制的 边 然后从 ...

  8. npm与nrm

    npm npm是Node.js 平台的默认包(模块依赖)管理工具 Node Package Manager nrm 一个npm的源管理器(管理工具) 允许快速的在 npm 源间切换 两者关系 npm是 ...

  9. [Android] Android 卡片式控件CardView的优雅使用

    [Android] Android 卡片式控件CardView的优雅使用 CardView是在安卓5.0提出的卡片式控件 其具体用法如下: 1.在app/build.gradle 文件中添加 comp ...

  10. React Native的语法之ES5和ES6

    原文地址:http://www.devio.org/2016/08/11/React-Native%E4%B9%8BReact%E9%80%9F%E5%AD%A6%E6%95%99%E7%A8%8B- ...