· 6 years ago · Nov 02, 2018, 05:34 AM
1curl -i -H "Accept:application/json" -H "Content-Type: application/json" "http://localhost:8080/api/auth/authorize?client_id=ng-zero&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fcallback&response_type=code&scope=read_profile" -X POST -d "{ "username" : "xxxx@yahoo.se", "password" : "xxxxxx" }"
2
3/oauth/authorize -> /auth/authorize
4/oauth/token -> /auth/token
5
6@EnableWebSecurity
7@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "xxx.xxxxxxxxx.user.rest.service", "xxx.xxxxxxxxx.user.rest.filter" })
8public class SecurityAuthorizationServerConfiguration extends WebSecurityConfigurerAdapter {
9
10 @Autowired
11 private UserDetailsService userDetailsService;
12
13 @Bean
14 public PasswordEncoder passwordEncoder() {
15 return PasswordEncoderFactories.createDelegatingPasswordEncoder();
16 }
17
18 @Bean
19 @Override
20 public AuthenticationManager authenticationManagerBean() throws Exception {
21 return super.authenticationManagerBean();
22 }
23
24 @Override
25 public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
26 authenticationManagerBuilder.userDetailsService(userDetailsService)
27 .passwordEncoder(passwordEncoder());
28 }
29
30 @Autowired
31 private RESTAuthenticationEntryPoint restAuthenticationEntryPoint;
32
33 @Override
34 public void configure(WebSecurity webSecurity) throws Exception {
35 webSecurity.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
36 }
37
38 @Override
39 public void configure(HttpSecurity http) throws Exception {
40 http
41 .csrf()
42 .disable()
43 .formLogin().disable()
44 .httpBasic().disable()
45 .logout().disable();
46
47 http.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint);
48
49 http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
50
51 http
52 .authorizeRequests()
53 .antMatchers(getUnsecuredPaths().toArray(new String[]{})).permitAll()
54 .antMatchers(RESTConstants.SLASH + DomainConstants.AUTH + RESTConstants.SLASH + DomainConstants.TOKEN).authenticated()
55 }
56
57 private List<String> getUnsecuredPaths() {
58 List<String> unsecuredPaths = Arrays.asList(
59 RESTConstants.SLASH + DomainConstants.AUTH + RESTConstants.SLASH + DomainConstants.LOGIN
60 );
61 return unsecuredPaths;
62 }
63
64}
65
66@Configuration
67@EnableAuthorizationServer
68public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
69
70 static final String CLIENT_ID = "ng-zero";
71 static final String CLIENT_SECRET = "secret";
72 static final String GRANT_TYPE_PASSWORD = "password";
73 static final String GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code";
74 static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
75
76 @Autowired
77 private PasswordEncoder passwordEncoder;
78
79 @Autowired
80 private AuthenticationManager authenticationManager;
81
82 @Autowired
83 private JwtProperties jwtProperties;
84
85 @Autowired
86 private UserDetailsService userDetailsService;
87
88 @Autowired
89 private TokenAuthenticationService tokenAuthenticationService;
90
91 @Override
92 public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
93 clients.inMemory()
94 .withClient(CLIENT_ID)
95 .secret(CLIENT_SECRET)
96 .redirectUris("http://localhost:4200/callback")
97 .authorizedGrantTypes(GRANT_TYPE_PASSWORD, GRANT_TYPE_AUTHORIZATION_CODE, GRANT_TYPE_REFRESH_TOKEN)
98 .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
99 .resourceIds("user-rest")
100 .scopes("read_profile", "write_profile", "read_firstname")
101 .accessTokenValiditySeconds(jwtProperties.getAccessTokenExpirationTime())
102 .refreshTokenValiditySeconds(jwtProperties.getRefreshTokenExpirationTime());
103 }
104
105 @Override
106 public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
107 security
108 .tokenKeyAccess("permitAll()")
109 .checkTokenAccess("isAuthenticated()")
110 .allowFormAuthenticationForClients();
111 }
112
113 @Override
114 public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
115 endpoints
116 .authenticationManager(authenticationManager)
117 .tokenServices(tokenServices())
118 .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
119 .tokenEnhancer(jwtAccessTokenConverter())
120 .accessTokenConverter(jwtAccessTokenConverter())
121 .userDetailsService(userDetailsService);
122
123 endpoints
124 .pathMapping("/oauth/authorize", RESTConstants.SLASH + DomainConstants.AUTH + RESTConstants.SLASH + DomainConstants.AUTHORIZE)
125 .pathMapping("/oauth/token", RESTConstants.SLASH + DomainConstants.AUTH + RESTConstants.SLASH + DomainConstants.TOKEN);
126 }
127
128 class CustomTokenEnhancer extends JwtAccessTokenConverter {
129
130 @Override
131 public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
132 User user = (User) authentication.getPrincipal();
133 Map<String, Object> info = new LinkedHashMap<String, Object>(accessToken.getAdditionalInformation());
134 info.put("email", user.getEmail());
135 info.put(CommonConstants.JWT_CLAIM_USER_EMAIL, user.getEmail().getEmailAddress());
136 info.put(CommonConstants.JWT_CLAIM_USER_FULLNAME, user.getFirstname() + " " + user.getLastname());
137 info.put("scopes", authentication.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList()));
138 DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken);
139 customAccessToken.setAdditionalInformation(info);
140 customAccessToken.setExpiration(tokenAuthenticationService.getExpirationDate());
141 return super.enhance(customAccessToken, authentication);
142 }
143
144 }
145
146 @Bean
147 public TokenStore tokenStore() {
148 return new JwtTokenStore(jwtAccessTokenConverter());
149 }
150
151 @Bean
152 public JwtAccessTokenConverter jwtAccessTokenConverter() {
153 JwtAccessTokenConverter jwtAccessTokenConverter = new CustomTokenEnhancer();
154 jwtAccessTokenConverter.setKeyPair(new KeyStoreKeyFactory(new ClassPathResource(jwtProperties.getSslKeystoreFilename()), jwtProperties.getSslKeystorePassword().toCharArray()).getKeyPair(jwtProperties.getSslKeyPair()));
155 return jwtAccessTokenConverter;
156 }
157
158 @Bean
159 @Primary
160 public DefaultTokenServices tokenServices() {
161 DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
162 defaultTokenServices.setTokenStore(tokenStore());
163 defaultTokenServices.setSupportRefreshToken(true);
164 defaultTokenServices.setTokenEnhancer(jwtAccessTokenConverter());
165 return defaultTokenServices;
166 }
167
168}