首页 > 其他分享 >登陆接口实现返回token

登陆接口实现返回token

时间:2023-08-18 23:00:22浏览次数:28  
标签:login 接口 token 登陆 import security com public user

自定义登陆接口,然后让SpringSecurity对这个接口放行,让用户访问这个接口的时候不用登录也能访问。

在接口中我们通过AuthenticationManager的authenticate方法来进行用户认证,所以需要在SecurityConfig中配置把AuthenticationManager注入容器。

认证成功的话要生成一个jwt,放入响应中返回。并且为了让用户下回请求时能通过jwt识别出具体的是哪个用户,我们需要把用户信息存入redis,可以把用户id作为key。

@RestController
public class LoginController {

    @Autowired
    private LoginServcie loginServcie;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        return loginServcie.login(user);
    }
}
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

LoginService
package com.security.service;

import com.security.domain.ResponseResult;
import com.security.domain.User;

public interface LoginService {

    ResponseResult login(User user);
}

 

LoginServiceImpl 
package com.security.service.impl;

import com.security.domain.LoginUser;
import com.security.domain.ResponseResult;
import com.security.domain.User;
import com.security.service.LoginService;
import com.security.utils.JwtUtil;
import com.security.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //AuthenticationManager authenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过,给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过,使用userid生成一个jwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        Map<String,String> map = new HashMap<>();
        map.put("token", jwt);
        //把完整的用户信息存入redis,userid作为key
        redisCache.setCacheObject("login:"+userId,loginUser);
        return new ResponseResult(200,"登录成功",map);
    }
}

 

 

 

标签:login,接口,token,登陆,import,security,com,public,user
From: https://www.cnblogs.com/ixtao/p/17641781.html

相关文章

  • C#.Net6 WebAPI制作简单自定义Token验证
    一、创建自定义类MyMiddleware继承中间件IMiddleware并实现接口二、在实现接口中的方法编写Token验证逻辑三、在WebAPI的Program类中的builder里注入自定义的类和app里配置自定义中间件builder.Services.AddScoped(typeof(MyMiddleware));app.UseMiddleware(typeof(MyMidd......
  • 业务开发时,接口不能对外暴露怎么办?
    在业务开发的时候,经常会遇到某一个接口不能对外暴露,只能内网服务间调用的实际需求。面对这样的情况,我们该如何实现呢?今天,我们就来理一理这个问题,从几个可行的方案中,挑选一个来实现。推荐一个开源免费的SpringBoot实战项目:https://github.com/javastacks/spring-boot-best-p......
  • 文字转语音 - 搭建微软tts整合web服务提供api接口(免费)
     微软tts是业界公认文字转语音效果最佳本文使用docker搭建微软tts服务并提供api接口对外提供服务对接官方免费在线体验接口,搭建后可免费进行调用使用,不保证永久稳定可用调用方式url:http://127.0.0.1:5003/ttsmethod:POST参数 类型 描述text string 语音文字内容voiceName stri......
  • 基于 JWT + Refresh Token 的用户认证实践(转载)
    HTTP是一个无状态的协议,一次请求结束后,下次在发送服务器就不知道这个请求是谁发来的了(同一个IP不代表同一个用户),在Web应用中,用户的认证和鉴权是非常重要的一环,实践中有多种可用方案,并且各有千秋。 基于Session的会话管理在Web应用发展的初期,大部分采用基于Session......
  • Airtest的iOS实用接口介绍
    1.前言前段时间Airtest更新了1.3.0.1版本,里面涉及非常多的iOS功能新增和改动,今天想详细跟大家聊一下里面的iOS设备接口。PS:本文示例均使用本地连接的iOS设备,Airtest版本为1.3.0.1。2.安装接口:install、install_appAirtest支持通过本地.ipa文件安装APP,也支持通过下载链接安......
  • windows10 登陆FTP成功后总是打开两个窗口
     具体现象:使用windows资源管理器打开登陆FTP,登陆FTP成功后当前窗口显示此文件夹为空,不在当前窗口显示文件夹内容,却在当前窗口后重新打开了一个资源管理器窗口显示FTP文件夹内容 解决方法:在资源管理器中输入地址时加上用户名,比如ftp://[email protected] ......
  • t113-c-lvgl触摸接口接入
    整合一下最近搞的东西,顺便设计一下ui移植触摸复制port文件到src目录下同时改名字和删除掉不用的东西:/***@filelv_port_indev_templ.c**//*Copythisfileas"lv_port_indev.c"andsetthisvalueto"1"toenablecontent*/#if1/**********************......
  • 2023年第 16期《Python接口自动化+Playwright 》课程,9月10号开学(课程全面升级!)!
    2023年第16期《Python接口自动化+Playwright》课程课程,9月10号开学(课程全面升级!)主讲老师:上海-悠悠上课方式:微信群视频在线教学,方便交流本期上课时间:2023年9月10号-2023年12月3号,晚上20:30-22:30报名费:报名费3000一人(周期3个月)联系微信/QQ:283340479课表如下直播课程主......
  • 使用protobuf生成各大厂的开放平台接口
    protoc-gen-go_api一款用protobuf文件生成go的http调用代码。具体代码见protoc-gen-go_api安装goinstallgithub.com/dev-openapi/protoc-gen-go_api@latest使用依赖googleapis的http.proto和annotations.proto。并且需要放到google/api/目录下如果google/api是在工程文......
  • 使用数据库的优化版php登陆系统
    title:使用数据库的优化版php登陆系统date:2023-07-3112:56:41categories:CTF-Web入门description:数据库优化版本在学习了MySQL以后,我尝试在原来的简易登陆系统上加入数据库。因为原来的账号密码都存在php文件的数组里嘛,现在存在了数据库里。网站依旧是用phpstudy集成......