要求:访问页面时,如果没有登录,则跳转到登录界面,如果是访问一个请求却没有登录,则返回一个401状态码和错误信息。
首先,需要先写一个controller类,用来接收未登录的用户需要的登录处理:
package com.chenjw.security.securityweb.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
@RestController
public class securityController {
//用来获取当前请求的session请求
private RequestCache requestCache = new HttpSessionRequestCache();
//用来实现界面的跳转
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
/**
* @throws IOException
* @Description: 当需要身份认证时跳转到这里
* @date: 2020-03-14
* @param request
* @param response
* @return
* @throws
*/
@RequestMapping("/authentication/request")
@ResponseStatus(code = HttpStatus.UNAUTHORIZED) //如果没有跳转,则返回请求401,UNAUTHORIZED就是401
public String RequireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取引发跳转的请求
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest != null) {
//得到引发跳转的请求
String redirectUrl = savedRequest.getRedirectUrl();
//判断跳转请求的url是否为一个页面
if (redirectUrl.endsWith(".html")) {
String url = "/mylogin.html";
redirectStrategy.sendRedirect(request, response, url);
}
}
JSONObject json = new JSONObject();
json.put("data", "访问的服务需要身份认证,清引导用户到登陆页!");
return JSONObject.toJSONString(json);
}
}
这样,就可以根据用户的请求,是否以html结尾里判断是否需要跳转页面或返回提示信息,
当我们写完了这个类后,下一步就是把验证的请求转到这里,让/authentication/request来代替登录页:
/**
* 自定义配置
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() //基于Form表单登录验证
.loginPage("/authentication/request") //自定义登录页
.loginProcessingUrl("/login") //表单提交相匹配,否则无法登录
.and()
.authorizeRequests()
.antMatchers("/mylogin.html","/authentication/request").permitAll() //防止登录页也需要进行登录验证,添加这个说明登录页不进行验证
.anyRequest()
.authenticated()
.and()
.csrf().disable(); // 关闭spring security的跨站伪造防护功能
}
当然,如果登录页页需要根据要显示的界面分别定义,则需要定义多个界面,分别进行判断,可以考虑注入多个url,然后判断后进行跳转就可以,关于登录页的自定义配置方式,可以使用SecurityProperties配置类,也可以直接使用自定义注入都可以。