首页 > 其他分享 >P.16-登录接口代码实现、P.17-测试接口

P.16-登录接口代码实现、P.17-测试接口

时间:2023-04-25 19:33:06浏览次数:38  
标签:登录 jwt 用户 接口 P.17 P.16 user public

P.16-登录接口代码实现

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

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

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

@RestController
public class LoginController {

    @Autowired
    private LoginServcie loginServcie;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        //登录
        return loginServcie.login(user);
    }
}

   SecurityConfig

@Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @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();
    }
}

   创建LoginServcie和LoginServcieImpl层

public interface LoginServcie {
    ResponseResult login(User user);//登录
}

 

 

@Service
public class LoginServcieImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

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

 加解密工具类内有

public static void main(String[] args) throws Exception {
//        String jwt = createJWT("123");
        Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZTQ1OTY1NzdkYWM0NTVhYWE5MGIzY2FmMmQ5ZGE5MiIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY4MjQxMzkyMywiZXhwIjoxNjgyNDE3NTIzfQ.NwiAzQY_8itMEgniIAQkY3W2FXWKG3uxKgeRLiv_gWs");
        String subject = claims.getSubject();
        System.out.println(subject);
//        System.out.println(jwt);
//        System.out.println(claims);
    }

P.17-测试接口

运行项目工程

  打开Redis和Postman进行测试运行

 运行结果

   将乱码进行替换到JwtUtil工具类里的

 运行出的结果是否是登录的用户id

 

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

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

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

标签:登录,jwt,用户,接口,P.17,P.16,user,public
From: https://www.cnblogs.com/agzq/p/17353614.html

相关文章

  • C++语言亚马逊国际获取AMAZON商品详情 API接口
    跨境电子商务是一种全新的互联网电商模式,运用电子化方式促成线上跨境交易,利用跨境物流运送商品,有利于打破传统的贸易格局,成为新的经济增长点。对我国来说,跨境电商平台正用一种全新的力量改变我国产业链的结构,并有利于增加贸易机会,拓展我国外贸在国际市场的广度与深度,赢得广阔的海......
  • 记php调用chatgpt接口
    $openai_api_key='your_openai_api_key_here';$engine='davinci';//ChatGPT中的AI模型名称$prompt='Hello,canyouhelpme?';//ChatGPT中的提示信息//构造请求数据$data=array('model'=>$engine,'prompt&#......
  • P.13-用户密码加密存储密码、P.14-铺垫知识jwt工具类使用、P.15-登录接口实现细节分析
    P.13-用户密码加密存储密码实际项目中我们不会把密码明文存储在数据库中。默认使用的PasswordEncoder要求数据库中的密码格式为:{id}password。它会根据id去判断密码的加密方式。但是我们一般不会采用这种方式。所以就需要替换PasswordEncoder。我们一般......
  • java学习之七:使用匿名类直接new接口
    ......
  • Java代码虾皮item_search-根据关键词获取商品列表 API 接口(title商品标题、pic_url宝
     Shopee是东南亚最大的电商平台之一。Shopee拥有商品种类,包括电子消费品、家居、美容保健、母婴、服饰及健身器材等。做好shopee店铺需要注意以下几点:1.选择优质的产品2.每日上新产品3.营销策略4.引流策略5.发货的地点Java代码操作示例importjava.io.BufferedReader;impo......
  • 产品经理需要了解api接口的哪些东西
    一、作为产品经理,需要了解API接口的以下方面:功能:API接口的功能是指它提供的业务功能,包括数据查询、修改、增加、删除、计算等等,根据产品的需求确定需要调用哪些API接口。请求方式和传参:API接口的请求方式包括GET、POST、PUT、DELETE等,根据功能需要选择对应的请求方式。传参指的是使......
  • 公有云LB健康检测接口配置
    server{listen8081;server_name127.0.0.1172.30.*172.31.*10.68.*;#LB网段location/nginx_status{stub_statuson;access_logoff;allow127.0.0.1;denyall;}location/status{......
  • 【HMS Core】Health Kit取消授权接口怎么辨识是哪个用户取消授权呢?
    【问题描述1】取消授权接口怎么辨识是哪个用户取消授权呢? 【解决方案】取消授权时,请求头中需要传入access_token,此access_token对应某个用户。详情请查看取消授权接口:https://developer.huawei.com/consumer/cn/doc/development/HMSCore-References/cancel-scpoes-00000010......
  • 接口测试工具-Postman使用详解
    ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。......
  • 登录接口实现细节分析与登录接口代码实现
    登录接口实现细节分析登陆接口接下我们需要自定义登陆接口,然后让SpringSecurity对这个接口放行,让用户访问这个接口的时候不用登录也能访问。​在接口中我们通过AuthenticationManager的authenticate方法来进行用户认证,所以需要在SecurityConfig中配置把Authe......