根据用户名称实现单点登录

一、参数格式

二、后端实现

复制代码
Controller层
java 复制代码
public class IAccessTokenLoginController extends BaseController {


    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISingleTokenServiceImpl tokenService;

    /**
     * 登录方法
     *
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult singleLogin(@RequestBody LoginBody loginBody) {

        String accessToken = loginBody.getAccessToken();
        if (StringUtils.isNotEmpty(accessToken)) {
            String tokenNew = tokenService.singleLogin(accessToken);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, tokenNew);
            return ajax;

        } else {
            return AjaxResult.error();
        }


    }
}
复制代码
注意:LoginBody新增变量accessToken
java 复制代码
@Service
public class ISingleTokenServiceImpl implements ISingleTokenService {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AuthenticationManager authenticationManager;


    public String singleLogin(String accessToken) {
        // 用户验证
        Authentication authentication = null;
        String username =accessToken;
        try
        {
//            username=parseAccessToken(accessToken);
//不用进行处置 直接传参
            authentication = authenticationManager
                    .authenticate(new IAuthenticationToken(username));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        return tokenService.createToken(loginUser);
    }

    public String parseAccessToken(String accessToken) {
        try {
            // 从 access token 中提取 payload
            Claims claims = Jwts.parser()
                    .parseClaimsJws(accessToken)
                    .getBody();

            // 获取 username
            String username = (String) claims.get("username");

            return username;
        } catch (Exception e) {
            System.out.println("无法解析 access token!" + e);
            return null;
        }
    }
  • 添加自定义IAuthenticationToken
java 复制代码
public class IAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal;

    public IAuthenticationToken(Object principal) {
        super(null);
        this.principal = principal;
        this.setAuthenticated(false);
    }

    public IAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }

}

添加IAuthenticationProvider
*

java 复制代码
@Component
public class IAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        IAuthenticationToken authenticationToken = (IAuthenticationToken) authentication;

        String username = (String) authenticationToken.getPrincipal();
        UserDetails user = userDetailsService.loadUserByUsername(username);
        IAuthenticationToken result = new IAuthenticationToken(user, Collections.emptyList());
        /*
        Details 中包含了 ip地址、 sessionId 等等属性 也可以存储一些自己想要放进去的内容
        */
        result.setDetails(authenticationToken.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return IAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

修改SecurityConfig 放行我们的请求登录路径 并把自定义认证加进来

.antMatchers("/hello","/single/login","/login", "/register", "/captchaImage").anonymous()

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception

{

复制代码
auth.authenticationProvider(new CustomLoginAuthenticationProvider(userDetailsService));
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
auth.authenticationProvider(iAuthenticationProvider);

}

  • 前端根据后台返回的token进行访问
相关推荐
超级大只老咪5 小时前
数组相邻元素比较的循环条件(Java竞赛考点)
java
小浣熊熊熊熊熊熊熊丶5 小时前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
毕设源码-钟学长6 小时前
【开题答辩全过程】以 公交管理系统为例,包含答辩的问题和答案
java·eclipse
啃火龙果的兔子6 小时前
JDK 安装配置
java·开发语言
星哥说事6 小时前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
派大鑫wink6 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
xUxIAOrUIII6 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
Dolphin_Home6 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法
醇氧6 小时前
org.jetbrains.annotations的@Nullable 学习
java·开发语言·学习·intellij-idea
Java&Develop6 小时前
Aes加密 GCM java
java·开发语言·python