前言
为啥要写这篇呢?昨天写了个security+jwt做token令牌及鉴权,其中登录认证是用自己的方法做的,只使用了授权校验,并没有用spring-security的登录认证。今天刚好有个水友碰到了登录认证的相关问题,帮忙解决后也在这里记一笔,方便以后回忆!!!
解决思路
- 自定义一个登录认证处理器
- 注入到security的登录认证管理器中(可以支持多个)
- 登录接口中,使用认证管理器进行登录认证(认证时会使用策略模式进行适配)
- 认证成功后,做一些业务处理(结合原有的token逻辑)
搞起来
1 自定义登录认证处理器
package com.zyu.boot.demo.security.handler;
import com.zyu.boot.demo.entity.User;
import com.zyu.boot.demo.mapper.UserMapper;
import com.zyu.boot.demo.security.entity.JwtUser;
import com.zyu.boot.demo.security.entity.Role;
import com.zyu.boot.demo.utils.pwd.PasswordHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
/**
* 自定义登录认证
*/
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserMapper userMapper;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String presentedPassword = (String)authentication.getCredentials();
JwtUser userDeatils = null;
// 根据用户名获取用户信息
User user = userMapper.selectByAccount(username);
String passwordEncrypt = userMapper.selectPasswordByAccount(username);
if (StringUtils.isEmpty(user)) {
throw new BadCredentialsException("用户名不存在");
} else {
ArrayList<Role> roles = new ArrayList<>();
roles.add(Role.valueOf(user.getRole()));
userDeatils = new JwtUser().setRole(roles).setUid(user.getUserid());
if (authentication.getCredentials() == null) {
throw new BadCredentialsException("登录名或密码错误");
}
try {
if (!PasswordHash.validatePassword(presentedPassword,passwordEncrypt)) {
throw new BadCredentialsException("登录名或密码错误");
}
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDeatils, authentication.getCredentials(), userDeatils.getAuthorities());
result.setDetails(authentication.getDetails());
return result;
}
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
2 security配置类的修改
ps:节约空间,只摘出了本地功能的配置
package com.zyu.boot.demo.security.config;
import com.zyu.boot.demo.security.filter.JwtAuthenticationTokenFilter;
import com.zyu.boot.demo.security.handler.JWTAuthenticationEntryPoint;
import com.zyu.boot.demo.security.handler.MyAccessDeniedHandler;
import com.zyu.boot.demo.security.handler.MyAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* SpringSecurity核心配置类
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//自定义认证处理器
@Autowired
private MyAuthenticationProvider myAuthenticationProvider;
/**
* 配置自定义认证处理
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.myAuthenticationProvider);
}
/**
* 认证管理器
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
3 登录接口中使用认证管理器认证
package com.zyu.boot.demo.controller;
import com.zyu.boot.demo.entity.User;
import com.zyu.boot.demo.security.entity.JwtUser;
import com.zyu.boot.demo.security.entity.Role;
import com.zyu.boot.demo.service.LoginService;
import com.zyu.boot.demo.utils.item.RespEntity;
import com.zyu.boot.demo.utils.token.JwtTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
@RestController
@RequestMapping("/login")
@Api(tags="登录接口")
public class LoginController {
@Autowired
private LoginService loginService;
/**
* 注入security认证管理器
*/
@Autowired
private AuthenticationManager authenticationManager;
@ApiOperation(value = "security登录", notes = "登录验证托管给security")
@ApiImplicitParams({
@ApiImplicitParam(name = "account", value = "用户名", required = true, paramType = "query"),
@ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query"),
})
@PostMapping("/securityLogin")
public RespEntity securityLogin(@RequestParam("account") String account, @RequestParam("password")String password, HttpServletRequest req){
/**
* 使用security的认证管理器进行认证
*/
Authentication authenticate = null;
try {
authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(account, password));
} catch (DisabledException | BadCredentialsException e) {
return new RespEntity(-1,"账户名或密码错误",null);
}
if(authenticate == null){
return new RespEntity(-1,"账户名或密码错误",null);
}
//存储认证信息
SecurityContextHolder.getContext().setAuthentication(authenticate);
//生成token
final JwtUser user = (JwtUser) authenticate.getPrincipal();
if(user != null){
// token信息保存在request域,随后保存在响应头
String token = JwtTokenUtils.createToken(user, false);
req.setAttribute("currentUser", user);
req.setAttribute(JwtTokenUtils.TOKEN_HEADER, token);
return new RespEntity(user);
}
return new RespEntity(-1,"账户名或密码错误",null);
}
}
验证一下
- 可以看到和我们原来的登录处理模式是一样的,做到了兼容
扩展性
这个登录认证还是很具有扩展性的,比如可以对接企业微信认证、QQ认证等第三方认证系统,我们要做的就仅仅是重新写个自定义认证处理器,在接口中引用这个就ok了。采用同一套认证模式,可以具备很好的扩展性。
结束语
别忘了用git保存一下,好习惯