Guest User

Untitled

a guest
Oct 24th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.83 KB | None | 0 0
  1. @Configuration
  2. @EnableAuthorizationServer
  3. public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  4.  
  5. static final String CLIEN_ID = "goodEApp-client";
  6. static final String CLIENT_SECRET = "goodEApp-secret";
  7. static final String GRANT_TYPE_PASSWORD = "password";
  8. static final String AUTHORIZATION_CODE = "authorization_code";
  9. static final String REFRESH_TOKEN = "refresh_token";
  10. static final String IMPLICIT = "implicit";
  11. static final String SCOPE_READ = "read";
  12. static final String SCOPE_WRITE = "write";
  13. static final String TRUST = "trust";
  14. static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60*60;
  15. static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
  16.  
  17. @Autowired
  18. private AuthenticationManager authenticationManager;
  19.  
  20. @Bean
  21. public JwtAccessTokenConverter accessTokenConverter() {
  22. JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
  23. converter.setSigningKey("as466gf");
  24. return converter;
  25. }
  26.  
  27. @Bean
  28. public TokenStore tokenStore() {
  29. return new JwtTokenStore(accessTokenConverter());
  30. }
  31.  
  32. @Override
  33. public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
  34.  
  35. configurer
  36. .inMemory()
  37. .withClient(CLIEN_ID)
  38. .secret(new BCryptPasswordEncoder().encode(CLIENT_SECRET))
  39. .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT )
  40. .scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
  41. .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS).
  42. refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
  43. }
  44.  
  45. @Override
  46. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  47. endpoints.tokenStore(tokenStore())
  48. .authenticationManager(authenticationManager)
  49. .accessTokenConverter(accessTokenConverter());
  50. }
  51.  
  52.  
  53. }
  54.  
  55. @Configuration
  56. @EnableResourceServer
  57. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  58.  
  59. private static final String RESOURCE_ID = "resource_id";
  60.  
  61. @Override
  62. public void configure(ResourceServerSecurityConfigurer resources) {
  63. resources.resourceId(RESOURCE_ID).stateless(false);
  64. }
  65.  
  66. @Override
  67. public void configure(HttpSecurity http) throws Exception {
  68. http
  69. .anonymous().disable()
  70. .authorizeRequests()
  71. .antMatchers("/resources/**").permitAll()
  72. .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
  73. }
  74. }
  75.  
  76. @Configuration
  77. @EnableWebSecurity
  78. @EnableGlobalMethodSecurity(prePostEnabled = true)
  79. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  80.  
  81. @Autowired
  82. private DataSource dataSource;
  83.  
  84. @Override
  85. @Bean
  86. public AuthenticationManager authenticationManagerBean() throws Exception {
  87. return super.authenticationManagerBean();
  88. }
  89.  
  90. @Bean
  91. public BCryptPasswordEncoder bCryptPasswordEncoder() {
  92. return new BCryptPasswordEncoder();
  93. }
  94.  
  95. @Autowired
  96. public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
  97. auth.jdbcAuthentication().dataSource(dataSource)
  98. .usersByUsernameQuery("select username, password, enabled "
  99. + " from accounts where username=?")
  100. .authoritiesByUsernameQuery("select a.username, r.role "
  101. + "from accounts a, access_roles r "
  102. + "where a.username=? and a.id_access_role = r.id_access_role")
  103. .passwordEncoder(bCryptPasswordEncoder());
  104. }
  105.  
  106. @Override
  107. protected void configure(HttpSecurity http) throws Exception {
  108. http
  109. .csrf().disable()
  110. .anonymous().disable()
  111. .authorizeRequests()
  112. .antMatchers("/resources/**").permitAll()
  113. .and().exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
  114. }
  115.  
  116. @Bean
  117. public FilterRegistrationBean corsFilter() {
  118. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  119. CorsConfiguration config = new CorsConfiguration();
  120. config.setAllowCredentials(true);
  121. config.addAllowedOrigin("*");
  122. config.addAllowedHeader("*");
  123. config.addAllowedMethod("*");
  124. source.registerCorsConfiguration("/**", config);
  125. FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
  126. bean.setOrder(0);
  127. return bean;
  128. }
  129. }
  130.  
  131. @Injectable()
  132. export class AccountService {
  133. constructor(private http: HttpClient) {
  134. }
  135.  
  136. private baseUri = '//localhost:8081/account';
  137. private tokenUri = '//localhost:8081/oauth/token';
  138.  
  139. public getLoginToken(usernameCli: string, passwordCli: string) {
  140. let headers_object = new HttpHeaders();
  141. headers_object.append('Content-Type', 'application/x-www-form-urlencoded');
  142. headers_object.append("Authorization", "Basic " + btoa("goodEApp-client:goodEApp-secret"));
  143.  
  144. const httpOptions = {
  145. headers: headers_object
  146. };
  147.  
  148. const credentials = {username: usernameCli, password: passwordCli, grant_type: "password"};
  149.  
  150. return this.http.post<any>(this.tokenUri, credentials, httpOptions);
  151. }
  152.  
  153. public getLoggedAccount(){
  154. return this.http.get<Account>(this.baseUri + "/getLoggedAccount")
  155. }
  156. }
  157.  
  158. @Component({
  159. selector: 'app-login',
  160. templateUrl: './login.component.html',
  161. styleUrls: ['./login.component.scss']
  162. })
  163. export class LoginComponent implements OnInit {
  164. loginForm: FormGroup;
  165. loading = false;
  166. submitted = false;
  167. error = '';
  168.  
  169. constructor(
  170. private formBuilder: FormBuilder,
  171. private router: Router,
  172. private accountService: AccountService) {}
  173.  
  174. ngOnInit() {
  175. this.loginForm = this.formBuilder.group({
  176. username: ['', Validators.required],
  177. password: ['', Validators.required]
  178. });
  179.  
  180. }
  181.  
  182. get f() { return this.loginForm.controls; }
  183.  
  184. onSubmit() {
  185. this.submitted = true;
  186.  
  187. // stop here if form is invalid
  188. if (this.loginForm.invalid) {
  189. return;
  190. }
  191.  
  192. this.loading = true;
  193. this.accountService.getLoginToken(this.f.username.value, this.f.password.value)
  194. .pipe(first())
  195. .subscribe(
  196. data => {
  197. console.log(data.toString());
  198. },
  199. error => {
  200. this.error = error.toString();
  201. this.loading = false;
  202. });
  203. }
  204. }
  205.  
  206. @Override
  207. public void configure(WebSecurity web) throws Exception {
  208. web.ignoring().antMatchers(HttpMethod.OPTIONS);
  209. }
  210.  
  211. @Configuration
  212. public class CorsConfig {
  213. @Bean
  214. public FilterRegistrationBean corsFilterRegistrationBean() {
  215. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  216. CorsConfiguration config = new CorsConfiguration();
  217. config.applyPermitDefaultValues();
  218. config.setAllowCredentials(true);
  219. config.setAllowedOrigins(Arrays.asList("*"));
  220. config.setAllowedHeaders(Arrays.asList("*"));
  221. config.setAllowedMethods(Arrays.asList("*"));
  222. config.setExposedHeaders(Arrays.asList("content-length"));
  223. config.setMaxAge(3600L);
  224. source.registerCorsConfiguration("/**", config);
  225. FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
  226. bean.setOrder(0);
  227. return bean;
  228. }
  229. }
  230.  
  231. @Override
  232. protected void configure(HttpSecurity http) throws Exception {
  233. http
  234. .authorizeRequests()
  235. .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
  236. }
  237.  
  238. @EnableWebSecurity
  239. class SecurityConfig extends WebSecurityConfigurerAdapter {
  240.  
  241. CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
  242. @Override
  243. public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
  244. CorsConfiguration corsConfiguration = new CorsConfiguration();
  245. corsConfiguration.addAllowedOrigin("http://localhost:63342");
  246. corsConfiguration.addAllowedHeader("Authorization");
  247. corsConfiguration.setAllowedMethods(Arrays.asList("POST", "GET"));
  248. corsConfiguration.setMaxAge(3600L);
  249. return corsConfiguration;
  250. }
  251. };
  252.  
  253. .and().cors().configurationSource(corsConfigurationSource);
Add Comment
Please, Sign In to add comment