Tengo un estancamiento en Spring Security, sobre todo al activar HTTPS, no me deja loguearme por el módulo por defecto. Todo el código fuente lo tengo en la pregunta en inglés: https://stackoverflow.com/questions/63298729/https-403-access-denied-login-default-module-spring-security
Spring Console
2020-08-10 10:43:43.171 INFO 2956 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9898 (https) 8082 (http) with context path ''
2020-08-10 10:43:43.173 INFO 2956 --- [ restartedMain] c.p.conexiona.ConexionaApplication : Started ConexionaApplication in 9.651 seconds (JVM running for 12.344)
2020-08-10 10:43:43.175 DEBUG 2956 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Creating new Restarter for thread Thread[main,5,main]
2020-08-10 10:43:43.175 DEBUG 2956 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Immediately restarting application
2020-08-10 10:43:43.175 DEBUG 2956 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@6fd62c96
2020-08-10 10:43:43.175 DEBUG 2956 --- [ restartedMain] o.s.boot.devtools.restart.Restarter : Starting application com.practicas.conexiona.ConexionaApplication with URLs [file:/C:/Users/canro/IdeaProjects/conexiona_cuatro/target/classes/]
2020-08-10 10:54:41.273 INFO 2956 --- [io-9898-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-10 10:54:41.273 INFO 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-10 10:54:41.273 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2020-08-10 10:54:41.281 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-08-10 10:54:41.281 INFO 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
2020-08-10 10:54:41.317 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2020-08-10 10:54:41.325 DEBUG 2956 --- [io-9898-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-08-10 10:54:41.353 DEBUG 2956 --- [io-9898-exec-10] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-08-10 10:54:41.361 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 403
2020-08-10 10:54:41.697 DEBUG 2956 --- [nio-9898-exec-2] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2020-08-10 10:54:41.909 DEBUG 2956 --- [nio-9898-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-08-10 10:54:41.917 DEBUG 2956 --- [nio-9898-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-08-10 10:54:41.921 DEBUG 2956 --- [nio-9898-exec-2] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 403
Application.class
@Configuration
public class Application {
public static void main(String... args) {
SpringApplication application = new SpringApplication(Application.class);
application.setAdditionalProfiles("ssl");
application.run(args);
}
@Bean
public ServletWebServerFactory servletContainer() {
// Enable SSL Trafic
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
// Add HTTP to HTTPS redirect
tomcat.addAdditionalTomcatConnectors(httpToHttpsRedirectConnector());
return tomcat;
}
/*
We need to redirect from HTTP to HTTPS. Without SSL, this application used
port 8082. With SSL it will use port 8443. So, any request for 8082 needs to be
redirected to HTTPS on 9898.
*/
private Connector httpToHttpsRedirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8082);
connector.setSecure(false);
connector.setRedirectPort(9898);
return connector;
}
application.properties
server.port=9898
# The format used for the keystore. It could be set to JKS in case it is a JKS file
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store= src/main/resources/crmiguez.p12
# The password used to generate the certificate
server.ssl.key-store-password=password
# The alias mapped to the certificate
server.ssl.key-alias=crmiguez
server.ssl.enabled=true
#trust store location
trust.store= src/main/resources/crmiguez.p12
#trust store password
trust.store.password=password
SecurityConfiguration.class
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private UserPrincipalDetailsService userPrincipalDetailsService;
private UserRepository userRepository;
public SecurityConfiguration(UserPrincipalDetailsService userPrincipalDetailsService, UserRepository userRepository) {
this.userPrincipalDetailsService = userPrincipalDetailsService;
this.userRepository = userRepository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
// remove csrf and state in session because in jwt we do not need them
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// add jwt filters (1. authentication, 2. authorization)
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository))
.authorizeRequests()
// configure access rules
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers( "/api/v1/usermanage/**").hasRole("GUEST")
.antMatchers( "/api/v1/accountmanage/**").hasRole("ADMIN")
.antMatchers("/api/v1/usermanage/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
@Bean
DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailsService);
return daoAuthenticationProvider;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
La configuración JWT es la misma que Romanian Coder código fuente
User.java (en esta clase he hecho dos getters para el tema de permisos y roles, en sendas listas)
@Entity(name = "User")
@Table
public class User implements Serializable {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Size(max = 36)
@Column(name = "userId")
private String userId;
@JoinColumn(name = "accountId", referencedColumnName = "accountId", nullable = false)
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JsonInclude(JsonInclude.Include.NON_NULL)
private Account account;
@Column(name = "userName")
private String userName;
@Column(name = "emailAddress")
private String emailAddress;
@Column(name = "password")
private String password;
@Column(name = "enabled")
@ColumnDefault(value = "1")
private Integer enabled;
@Column(name = "lastLogin")
private Long lastLogin;
@OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<UserGroupUser> userGroups = new HashSet<>();
public User() {
}
public User (String userId, String accountId, String userName, String emailAddress, String password, Integer enabled, Long lastLogin) {
this.userId = userId;
this.account = new Account(accountId);
this.userName = userName;
this.emailAddress = emailAddress;
this.password = password;
this.enabled = enabled;
this.lastLogin = lastLogin;
}
public User(String userId, Account account, String userName, String emailAddress, String password, Integer enabled, Long lastLogin) {
this.userId = userId;
this.account = account;
this.userName = userName;
this.emailAddress = emailAddress;
this.password = password;
this.enabled = enabled;
this.lastLogin = lastLogin;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Account getAccount() { return account; }
public void setAccount(Account account) { this.account = account; }
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getEnabled() {
return enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
public Long getLastLogin() {
return lastLogin;
}
public void setLastLogin(Long lastLogin) {
this.lastLogin = lastLogin;
}
public Set<UserGroupUser> getUserGroups() {
return userGroups;
}
public void setUserGroups(Set<UserGroupUser> userGroupUser) {
this.userGroups = userGroupUser;
}
public List<String> getRoleList(){
List<String> userRoleList = new ArrayList<>();
if(this.userGroups.size() > 0){
for (UserGroupUser usu: userGroups) {
if (usu.getUserAdmin() == 1)
userRoleList.add("ADMIN");
else
userRoleList.add("GUEST");
}
return userRoleList;
}
return new ArrayList<>();
}
public List<String> getPermissionList(){
List<String> userPermissionsList = new ArrayList<>();
if(this.userGroups.size() > 0){
for (UserGroupUser usu: userGroups) {
if (usu.getUserAdmin() == 1){
userPermissionsList.add("ACCOUNT_WRITE");
userPermissionsList.add("ACCOUNT_READ");
userPermissionsList.add("USER_WRITE");
userPermissionsList.add("USER_READ");
}
else{
userPermissionsList.add("USER_READ");
}
}
return userPermissionsList;
}
return new ArrayList<>();
}
}
Comandos consola SO para archivo p12
keytool -genkeypair -alias crmiguez -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore crmiguez.p12 -validity 3650
keytool -genkeypair -alias crmiguez -keyalg RSA -keysize 2048 -keystore crmiguez.jks -validity 3650
keytool -importkeystore -srckeystore crmiguez.jks -destkeystore crmiguez.jks -deststoretype pkcs12
Similar questions in Stackoverflow: https://stackoverflow.com/questions/58710908/jwt-token-in-spring-boot-configuration-problem
https://stackoverflow.com/questions/31746466/spring-security-always-returns-http-403/41247428
If I put https://localhost:9898/login on the browser, it appears like this:
403 Denied on login Spring Security
In case of Insomnia, the error was the following:
Proving login module in Insomnia App
Muchas gracias. :)
Actualizado 11-8-20: He añadido GET, pero ha cambiado a 404
.../login
, pero no una petición GET, que es lo que tu navegador intenta cuando pones una URL en la barra de direcciones