一、自定义登陆页面,并登陆
在 WebSecurityConfig 中更改配置,如果不知道我改了什么,请到 spring boot 之 security(一) 对比。
package com.wt.cloud.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 功能描述: WebSecurityConfigurerAdapter web安全应用的适配器
* @author : big uncle
* @date : 2019/10/10 10:26
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭默认的basic认证拦截
// http
// .authorizeRequests()
// .anyRequest()
// .permitAll().and()
// .logout()
// .permitAll();
// 让使用form表单认证
http.formLogin()
// 自定义登陆页面
.loginPage("/login.html")
// 覆盖spring security默认登陆地址。默认是login
.loginProcessingUrl("/auth/login")
.and()
// 以下都是授权的配置
.authorizeRequests()
// 剔除登陆页面的认证拦截,否则会在进登陆页面一直跳转;permitAll 指任何人都可以访问这个url
.antMatchers("/login.html","/auth/login").permitAll()
// 任何请求
.anyRequest()
// 都需要身份认证
.authenticated()
.and()
// 关闭跨站请求伪造拦截
.csrf().disable();
}
}
loginProcessingUrl 这个要跟大家单独说下,这个是覆盖spring security的默认登陆地址,也可以在我 spring boot 之 security(一) 中查看 security 的核心及原理,他会被第一层过滤器拦截 UsernamePasswordAuthenticationFilter,而想要正确被拦截,要么使用默认,要么自己覆盖。
然后新建一个login.html
内容大致如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/auth/login" method="post">
<input name="username"> 姓名
<br>
<input name="password"> 密码
<br>
<input type="submit" value="登陆" >
</form>
</body>
</html>
二、前后端分离怎么办
前后端分离逻辑图前后端分离只能给的是状态码,那我们应该怎么处理呢...
只需要把 WebSecurityConfig 中的 loginPage 配置我们自定义的 controller 即可
WebSecurityConfig
package com.wt.cloud.config;
import com.wt.cloud.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 功能描述: WebSecurityConfigurerAdapter web安全应用的适配器
* @author : big uncle
* @date : 2019/10/10 10:26
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProperties securityProperties;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭默认的basic认证拦截
// http
// .authorizeRequests()
// .anyRequest()
// .permitAll().and()
// .logout()
// .permitAll();
// 让使用form表单认证
http.formLogin()
// 自定义登陆页面
.loginPage("/web/authentication")
// 覆盖spring security默认登陆地址。默认是login
.loginProcessingUrl("/authentication/login")
.and()
// 以下都是授权的配置
.authorizeRequests()
// 剔除登陆页面的认证拦截,否则会在进登陆页面一直跳转;permitAll 指任何人都可以访问这个url
.antMatchers("/web/authentication",securityProperties.getWebProperties().getLoginPage()).permitAll()
// 任何请求
.anyRequest()
// 都需要身份认证
.authenticated()
.and()
// 关闭跨站请求伪造拦截
.csrf().disable();
}
}
自定义的controller
package com.wt.cloud.web;
import cn.hutool.core.util.StrUtil;
import com.wt.cloud.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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
@RequestMapping("/web")
@Slf4j
public class WebController {
/**
* 自定义的一些配置信息,如登陆页面等
*/
@Autowired
private SecurityProperties securityProperties;
/**
* 缓存了当前的请求
*/
private RequestCache requestCache = new HttpSessionRequestCache();
/**
*
*/
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* 功能描述: 当需要身份认证时 跳转到这里
* @author : big uncle
* @date : 2019/10/12 12:18
*/
@GetMapping("/authentication")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public String requireAuthenrication(HttpServletRequest request, HttpServletResponse response) throws Exception {
SavedRequest savedRequest = requestCache.getRequest(request,response);
if(savedRequest!=null){
String url = savedRequest.getRedirectUrl();
log.debug("引发的请求是 {}",url);
if(StrUtil.endWithIgnoreCase(url,".html")){
redirectStrategy.sendRedirect(request,response,securityProperties.getWebProperties().getLoginPage());
}
}
return "没有登陆,请登录";
}
}
三、自定义登陆成功处理
为什么要有自定义成功处理,因为现代都是前后端分离项目,spring 默认的是登陆成功跳转,我们不可能给前端跳转,所以我们自己处理登陆成功,响应登陆成功的json结果给前端。
自定义登陆成功需要实现 AuthenticationSuccessHandler 重写 onAuthenticationSuccess 方法。
自定义成功处理类
package com.wt.cloud.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
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;
/**
* 功能描述: 成功处理器
* @author : big uncle
* @date : 2019/10/12 14:18
*/
@Component
@Slf4j
public class MyAuthenticationSuccessHandle implements AuthenticationSuccessHandler {
@Autowired
private ObjectMapper objectMapper;
/**
* 功能描述: Authentication 封装用户的认证信息,ip,session,userDetail等
* @author : big uncle
* @date : 2019/10/12 14:13
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(authentication));
log.debug("登陆成功");
}
/**
* authentication 所包含信息
* {
* "authorities": [{ // 权限
* "authority": "admin"
* }],
* "details": {
* "remoteAddress": "0:0:0:0:0:0:0:1",
* "sessionId": null
* },
* "authenticated": true, // 认证通过
* "principal": { // userDetail的信息
* "password": null,
* "username": "admin",
* "authorities": [{
* "authority": "admin"
* }],
* "accountNonExpired": true,
* "accountNonLocked": true,
* "credentialsNonExpired": true,
* "enabled": true
* },
* "credentials": null,
* "name": "admin"
* }
*/
}
在 WebSecurityConfig 配置,先注入 MyAuthenticationSuccessHandle,在 formLogin 中再加 .successHandler(myAuthenticationSuccessHandle) 即可
四、自定义登陆失败处理
失败的配置和成功其实是一样的,只是实现的类换了 AuthenticationFailureHandler
失败自定义类
package com.wt.cloud.config;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
log.info("登陆失败");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("o failure");
}
}
WebSecurityConfig 的配置
package com.wt.cloud.config;
import com.wt.cloud.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 功能描述: WebSecurityConfigurerAdapter web安全应用的适配器
* @author : big uncle
* @date : 2019/10/10 10:26
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProperties securityProperties;
@Autowired
private MyAuthenticationSuccessHandle myAuthenticationSuccessHandle;
@Autowired
private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭默认的basic认证拦截
// http
// .authorizeRequests()
// .anyRequest()
// .permitAll().and()
// .logout()
// .permitAll();
// 让使用form表单认证
http.formLogin()
// 自定义登陆页面
.loginPage("/web/authentication")
// 覆盖spring security默认登陆地址。默认是login
.loginProcessingUrl("/authentication/login")
// 配置成功处理类
.successHandler(myAuthenticationSuccessHandle)
// 配置失败处理类
.failureHandler(myAuthenticationFailureHandler)
.and()
// 以下都是授权的配置
.authorizeRequests()
// 剔除登陆页面的认证拦截,否则会在进登陆页面一直跳转;permitAll 指任何人都可以访问这个url
.antMatchers("/web/authentication",securityProperties.getWebProperties().getLoginPage()).permitAll()
// 任何请求
.anyRequest()
// 都需要身份认证
.authenticated()
.and()
// 关闭跨站请求伪造拦截
.csrf().disable();
}
}
不是前端分离的改造
如果不是前端分离,则可以把 成功处理器 和 失败处理器的 实现 改成 继承,成功继承 SavedRequestAwareAuthenticationSuccessHandler,失败继承 SimpleUrlAuthenticationFailureHandler
成功
package com.wt.cloud.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 功能描述: 成功处理器
* @author : big uncle
* @date : 2019/10/12 14:18
*/
@Component
@Slf4j
public class MyAuthenticationSuccessHandle extends SavedRequestAwareAuthenticationSuccessHandler {
@Value("${cloud.web.dataType}")
private String dataType;
@Autowired
private ObjectMapper objectMapper;
/**
* 功能描述: Authentication 封装用户的认证信息,ip,session,userDetail等
* @author : big uncle
* @date : 2019/10/12 14:13
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 判断是否以json的形式给前端数据,还是直接跳转到成功页面
if(dataType.equalsIgnoreCase("json")) {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(authentication));
}else{
// 实现跳转
super.onAuthenticationSuccess(request,response,authentication);
}
log.debug("登陆成功");
}
/**
* authentication 所包含信息
* {
* "authorities": [{ // 权限
* "authority": "admin"
* }],
* "details": {
* "remoteAddress": "0:0:0:0:0:0:0:1",
* "sessionId": null
* },
* "authenticated": true, // 认证通过
* "principal": { // userDetail的信息
* "password": null,
* "username": "admin",
* "authorities": [{
* "authority": "admin"
* }],
* "accountNonExpired": true,
* "accountNonLocked": true,
* "credentialsNonExpired": true,
* "enabled": true
* },
* "credentials": null,
* "name": "admin"
* }
*/
}
失败
package com.wt.cloud.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 功能描述: 处理失败器
* @author : big uncle
* @date : 2019/10/12 14:54
*/
@Component
@Slf4j
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Value("${cloud.web.dataType}")
private String dataType;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// 判断是否以json的形式给前端数据,还是直接跳转到失败页面
if(dataType.equalsIgnoreCase("json")) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write(exception.getMessage());
}else {
super.onAuthenticationFailure(request,response,exception);
}
log.info("登陆失败");
}
}
网友评论