看完shiro,在看spring security感觉快了很多,最开始看spring security的时候,非常晕,看完我觉得spring security做了太多事,以至于程序员都不知道,是怎么实现的,这样的
后果就是 当出现错误,或者需要修改的时候感觉无从下手。
个人理解,若有错误,请指正。
spring security跟shiro类似,都是使用过滤器来认证和授权,不同的是spring seciruty是实现了一个过滤器链,每个请求都要经过,我们可以使用自动配置,这样spring security自动帮我们配置了这一系列过滤器,也可以自定义过滤器放在它的过滤器链中。
验证码或密码登录,需要重新修改认证过滤器
package com.test.hello.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class KdUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
private boolean postOnly = true;
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
String type = request.getParameter("j_type");
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
if (type == null) {
type = "1";
}
username = username.trim();
Authentication authRequest;
if(type.equals("1")){
authRequest = new UsernamePasswordAuthenticationToken(username, password);
}else{
authRequest = new KdUsernamePasswordAuthenticationToken(username, password,type);
}
// Allow subclasses to set the "details" property
setDetails(request, (AbstractAuthenticationToken)authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
/**
* Provided so that subclasses may configure what is put into the authentication request's details
* property.
*
* @param request that an authentication request is being created for
* @param authRequest the authentication request object that should have its details set
*/
protected void setDetails(HttpServletRequest request, AbstractAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
}
type为2时候,使用验证码登录,token- >provider ->
token
package com.test.hello.security;
import java.util.Collection;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
public class KdUsernamePasswordAuthenticationToken extends AbstractAuthenticationToken{
//~ Instance fields ================================================================================================
/**
*
*/
private static final long serialVersionUID = 1L;