🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 1.授权服务 ~~~ @Configuration @EnableAuthorizationServer // 授权服务 public class AuthorizationConfigurerAdapter extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Autowired private TokenStore tokenStore; /** * 客户端 * * @param clients * @throws Exception */ @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory()// 内存 .withClient("client_id")// 客户端id .secret(passwordEncoder.encode("123"))//客户端密钥 .resourceIds("add")// 客户端可以访问的资源列表 // 申请令牌的方式 .authorizedGrantTypes("password","authorization_code","implicit","client_credentials","refresh_token") .scopes("adm")// 授权范围 .autoApprove(false) // 申请授权码的时候不跳转到授权 .redirectUris("https://www.baidu.com");//授权码回调地址 } @Autowired private AuthenticationManager authenticationManager; @Autowired private AuthorizationCodeServices authorizationCodeServices; /** * 配置令牌端点 * * @param endpoints * @throws Exception */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints // 密码模式需要配置这个 .authenticationManager(authenticationManager) // 授权码模式 .authorizationCodeServices(authorizationCodeServices) //令牌服务 不管什么模式都需要 .tokenServices(authorizationServerTokenServices()) // 允许post提交 .allowedTokenEndpointRequestMethods(HttpMethod.POST); } /** * 令牌安全 * * @param security * @throws Exception */ @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security. // 公钥公开 tokenKeyAccess("permitAll()") // 认证token公开 .checkTokenAccess("permitAll()") // 允许表单申请令牌 .allowFormAuthenticationForClients(); } @Autowired public ClientDetailsService clientDetailsService; // 令牌管理服务 @Bean public AuthorizationServerTokenServices authorizationServerTokenServices() { DefaultTokenServices services = new DefaultTokenServices(); services.setClientDetailsService(clientDetailsService);// k+客户端信息服务 services.setSupportRefreshToken(true);// 是否产生刷新令牌 services.setTokenStore(tokenStore);//令牌存储策略 services.setAccessTokenValiditySeconds(7200);//令牌有效期 2小时 单位秒 services.setRefreshTokenValiditySeconds(259200);//刷新令牌有效期3天 return services; } } ~~~ # 2.密码模式配置 ~~~ @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JdbcUserDetailsServiceImpl jdbcUserDetailsService; @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(jdbcUserDetailsService); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ~~~ 3.其他配置 ~~~ @Bean public TokenStore tokenStore(){ return new InMemoryTokenStore(); } @Bean //授权码服务 public AuthorizationCodeServices authorizationCodeServices(){ return new InMemoryAuthorizationCodeServices(); } ~~~