阅读 162

JWT——JWT来存储token(无密码版)

文章目录

  • 1、pom(核心依赖)

  • 2、启动类

  • 3、配置文件application.yml

  • 4、配置授权服务器

  • 5、安全配置

  • 6、配置资源服务器

  • 7、测试资源服务器


注意:要想使用jwt,必须要使用私密钥,自行生成,谢谢!!!!!!!


1、pom(核心依赖)

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId></dependency><!-- web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>


2、启动类

package com.mysave.authorization;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;/**
 * @author zhz
 * @create 2021-03-13 17:27
 */@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})//加exclude = {DataSourceAutoConfiguration.class这个是因为我的依赖里面有mysql相关的,但是我这里不用public class AuthorizationApplication {public static void main(String[] args) {SpringApplication.run(AuthorizationApplication.class,args);}}


3、配置文件application.yml

server:
  port: 9999spring:
  application:name: authorization


4、配置授权服务器

注意:我里面的coinexchange.jks是我自己用java生成的私钥

package com.mysave.authorization.config.auth;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;/**
 * @author zhz
 * @create 2021-03-13 18:04
 */@Configuration@EnableAuthorizationServer//开启授权服务器功能public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate AuthenticationManager authenticationManager;

   // @Qualifier("userServiceDetailsServiceImpl")@Autowiredprivate UserDetailsService userDetailsService;//    @Autowired//    private RedisConnectionFactory redisConnectionFactory;/**
     * 添加第三方的客户端
     */@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory().withClient("coin-api") // 第三方客户端的名称.secret(passwordEncoder.encode("coin-secret")) //  第三方客户端的密钥.scopes("all") //第三方客户端的授权范围.accessTokenValiditySeconds(7 * 24 *3600) // token的有效期.refreshTokenValiditySeconds(30 * 24 * 3600)// refresh_token的有效期;super.configure(clients);}/**
     * 配置验证管理器,UserdetailService
     */@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService).tokenStore(jwtTokenStore())//数据存储在jwt中.tokenEnhancer(jwtAccessTokenConverter());super.configure(endpoints);}private TokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}public JwtAccessTokenConverter jwtAccessTokenConverter() {JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();//加载私钥ClassPathResource classPathResource = new ClassPathResource("coinexchange.jks");KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "coinexchange".toCharArray());tokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("coinexchange", "coinexchange".toCharArray()));return tokenConverter;}}


5、安全配置

package com.mysave.authorization.config.auth;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.password.NoOpPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.provisioning.InMemoryUserDetailsManager;import java.util.Arrays;/**
 * @author :zhz
 * @date :Created in 2021/03/14
 * @version: V1.0
 * @slogan: 天下风云出我辈,一入代码岁月催
 * @description:
 **/@Configurationpublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable();http.authorizeRequests().anyRequest().authenticated();}@Beanprotected AuthenticationManager authenticationManager() throws Exception {return super.authenticationManager();}@Beanprotected UserDetailsService userDetailsService(){InMemoryUserDetailsManager inMemoryUserDetailsManager=new InMemoryUserDetailsManager();User user=new User("admin","123456", Arrays.asList(new SimpleGrantedAuthority("Role_Admin")));inMemoryUserDetailsManager.createUser(user);return inMemoryUserDetailsManager;}/**
     * 密码加密
     * @return
     */@Beanpublic PasswordEncoder passwordEncoder(){return  NoOpPasswordEncoder.getInstance();//设置不加密方式}/*public static void main(String[] args) {
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        String encode = encoder.encode("123456");
        System.out.println(encode);
    }*/}


6、配置资源服务器

package com.mysave.authorization.config.auth;import lombok.extern.slf4j.Slf4j;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;import org.springframework.security.oauth2.provider.token.TokenStore;import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;import org.springframework.util.FileCopyUtils;import java.io.IOException;/**
 * @author zhz
 * @create 2021-03-13 17:54
 */@EnableResourceServer@Configurationpublic class ResourceServerConfig extends ResourceServerConfigurerAdapter {}


7、测试资源服务器

package com.mysave.authorization.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.security.Principal;/**
 * @author :zhz
 * @date :Created in 2021/03/15
 * @version: V1.0
 * @slogan: 天下风云出我辈,一入代码岁月催
 * @description:
 **/@RestControllerpublic class UserInfoController {/**
     * 当前的登录的用户对象
     */@GetMapping("/user/info")public Principal userInfo(Principal principal){//底层是使用ThreadLocal实现的//这里也可以用下面来替换principal//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();return principal;}}


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐