Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ public class MovieflixApplication {
public static void main(String[] args) {
SpringApplication.run(MovieflixApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.devsuperior.movieflix.components;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import com.devsuperior.movieflix.entities.User;
import com.devsuperior.movieflix.repositories.UserRepository;

@Component
public class JwtTokenEnhancer implements TokenEnhancer{

@Autowired
private UserRepository userRepository;

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

User user = userRepository.findByEmail(authentication.getName());

Map<String, Object> map = new HashMap<>();
map.put("userName", user.getName());
map.put("userId", user.getId());

DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
token.setAdditionalInformation(map);

return token;
}

}
35 changes: 35 additions & 0 deletions src/main/java/com/devsuperior/movieflix/config/AppConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.devsuperior.movieflix.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
public class AppConfig {

@Value("${jwt.secret}")
private String jwtSecret;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
tokenConverter.setSigningKey(jwtSecret);
return tokenConverter;
}

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



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.devsuperior.movieflix.config;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import com.devsuperior.movieflix.components.JwtTokenEnhancer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${jwt.duration}")
private Integer jwtDuration;

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Autowired
private JwtAccessTokenConverter accessTokenConverter;

@Autowired
private TokenStore tokenStore;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private JwtTokenEnhancer tokenEnhancer;

@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(clientId)
.secret(passwordEncoder.encode(clientSecret))
.scopes("read", "write")
.authorizedGrantTypes("password")
.accessTokenValiditySeconds(jwtDuration);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

TokenEnhancerChain chain = new TokenEnhancerChain();
chain.setTokenEnhancers(Arrays.asList(accessTokenConverter, tokenEnhancer));

endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter)
.tokenEnhancer(chain)
.userDetailsService(userDetailsService);
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.devsuperior.movieflix.config;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
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.store.JwtTokenStore;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{

@Autowired
private Environment env;

@Autowired
private JwtTokenStore tokenStore;

private static final String[] PUBLIC = { "/oauth/token", "/h2-console/**" };

@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenStore(tokenStore);
}

@Override
public void configure(HttpSecurity http) throws Exception {

// H2
if (Arrays.asList(env.getActiveProfiles()).contains("test")) {
http.headers().frameOptions().disable();
}

http.authorizeRequests()
.antMatchers(PUBLIC).permitAll()
.anyRequest().authenticated();

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.devsuperior.movieflix.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Autowired
private UserDetailsService userDetailService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
super.configure(auth);
}

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/actuator/**");
}

@Override
@Bean
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.devsuperior.movieflix.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.devsuperior.movieflix.dto.UserDTO;
import com.devsuperior.movieflix.services.UserService;

@RestController
@RequestMapping(value = "/users")
public class UserController {

@Autowired
private UserService service;

@GetMapping(value = "/profile")
public ResponseEntity<UserDTO> findCurrentUser(){
UserDTO dto = service.findCurrentUser();
return ResponseEntity.ok().body(dto);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.devsuperior.movieflix.controllers.exceptions;

import java.io.Serializable;

public class FieldMessage implements Serializable {
private static final long serialVersionUID = 1L;

private String fieldName;
private String message;

public FieldMessage() {}

public FieldMessage(String fieldName, String message) {
this.fieldName = fieldName;
this.message = message;
}

public String getFieldName() {
return fieldName;
}

public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.devsuperior.movieflix.controllers.exceptions;

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonProperty;

public class OAuthCustomError implements Serializable {
private static final long serialVersionUID = 1L;

private String error;

@JsonProperty("error_description")
private String errorDescription;

public OAuthCustomError() {
}

public OAuthCustomError(String error, String errorDescription) {
super();
this.error = error;
this.errorDescription = errorDescription;
}

public String getError() {
return error;
}

public void setError(String error) {
this.error = error;
}

public String getErrorDescription() {
return errorDescription;
}

public void setErrorDescription(String errorDescription) {
this.errorDescription = errorDescription;
}




}
Loading