Skip to content

Commit

Permalink
enable jwt token
Browse files Browse the repository at this point in the history
  • Loading branch information
zhang wanchao committed Mar 22, 2018
1 parent 0fad0b5 commit 34831ec
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 19 deletions.
22 changes: 21 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@
<groupId>com.revengemission.sso</groupId>
<artifactId>oauth2-server</artifactId>
<packaging>jar</packaging>
<name>sso-server</name>
<name>oauth2-server</name>
<description>oauth2-server with resource server</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<security.oauth2.version>2.3.0.RELEASE</security.oauth2.version>
<spring.security.jwt.version>1.0.9.RELEASE</spring.security.jwt.version>
</properties>


Expand All @@ -46,6 +48,12 @@
<version>${security.oauth2.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>${spring.security.jwt.version}</version>
</dependency>

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
Expand Down Expand Up @@ -85,6 +93,18 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
<nonFilteredFileExtension>woff</nonFilteredFileExtension>
<nonFilteredFileExtension>jkd</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
* https://projects.spring.io/spring-security-oauth/docs/oauth2.html
* */
@SpringBootApplication
public class SSOServertApplication {
public class Auth2ServertApplication {

public static void main(String[] args) {
SpringApplication.run(SSOServertApplication.class, args);
SpringApplication.run(Auth2ServertApplication.class, args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,100 @@

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
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.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
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;

import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

@Value("${access_token.validity_period:3600}") // 默认值3600
private int accessTokenValiditySeconds = 3600;

@Value("${refresh_token.validity_period:2592000}") // 默认值3600
private int refreshTokenValiditySeconds = 2592000;

@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;


@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter() {
/***
* 重写增强token方法,用于自定义一些token返回的信息
*/
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
String userName = authentication.getUserAuthentication().getName();
User user = (User) authentication.getUserAuthentication().getPrincipal();// 与登录时候放进去的UserDetail实现类一直查看link{SecurityConfiguration}
/** 自定义一些token属性 ***/
final Map<String, Object> additionalInformation = new HashMap<>();
additionalInformation.put("userName", userName);
additionalInformation.put("roles", user.getAuthorities());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
OAuth2AccessToken enhancedToken = super.enhance(accessToken, authentication);
return enhancedToken;
}

};
KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "keypass".toCharArray());
accessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));


//accessTokenConverter.setSigningKey("123");// 测试用,资源服务使用相同的字符达到一个对称加密的效果,生产时候使用RSA非对称加密方式
return accessTokenConverter;
}

@Bean
public TokenStore tokenStore() {
TokenStore tokenStore = new JwtTokenStore(accessTokenConverter());
return tokenStore;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

// @formatter:off
clients.inMemory()
.withClient("SampleClientId")
.authorizedGrantTypes("implicit", "authorization_code", "refresh_token")
.authorities("ROLE_USER", "ROLE_CLIENT","ROLE_TRUSTED_CLIENT")
//.authorizedGrantTypes("implicit", "authorization_code", "refresh_token", "password", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.secret("secret");
// @formatter:on
.secret("secret")
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.refreshTokenValiditySeconds(refreshTokenValiditySeconds);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.accessTokenConverter(accessTokenConverter());
endpoints.tokenStore(tokenStore());
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')")
.checkTokenAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ public PasswordEncoder passwordEncoder() {
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
//.passwordEncoder(new MyPasswordEncoder())//在此处应用自定义PasswordEncoder
.withUser("zhangsan").password("password").roles("USER", "CLIENT", "TRUSTED_CLIENT").and()
.withUser("lisi").password("password").roles("USER", "CLIENT", "TRUSTED_CLIENT");
.withUser("zhangsan").password("password").roles("USER").and()
.withUser("lisi").password("password").roles("USER");
}

@Override
Expand All @@ -39,10 +39,9 @@ public AuthenticationManager authenticationManagerBean() throws Exception {

@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/success", "/signIn", "/security_check").permitAll()
.antMatchers("/signIn", "/security_check").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling()
Expand All @@ -57,6 +56,5 @@ protected void configure(HttpSecurity http) throws Exception {
.failureUrl("/signIn?authentication_error=true")
.loginPage("/signIn").loginProcessingUrl("/security_check").permitAll().and()
.httpBasic().disable();
// @formatter:on
}
}
6 changes: 3 additions & 3 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
spring.thymeleaf.cache=false

logging.level.root=info
#server.servlet.context-path=/
access_token.validity_period=3600
refresh_token.validity_period=2592000
logging.level.root=info
Binary file added src/main/resources/jwt.jks
Binary file not shown.

0 comments on commit 34831ec

Please sign in to comment.