Merge pull request #8889 from Maiklins/JAVA-877-update-Redirect-after-login-article

Java-877 update redirect after login article
This commit is contained in:
Josh Cummings 2020-03-21 23:38:11 -06:00 committed by GitHub
commit ba6fa2e023
3 changed files with 62 additions and 52 deletions

View File

@ -2,6 +2,8 @@ package org.baeldung.security;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
@ -47,26 +49,21 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
} }
protected String determineTargetUrl(final Authentication authentication) { protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false; Map<String, String> roleTargetUrlMap = new HashMap<>();
roleTargetUrlMap.put("ROLE_USER", "/homepage.html");
roleTargetUrlMap.put("ROLE_ADMIN", "/console.html");
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) { for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true; String authorityName = grantedAuthority.getAuthority();
break; if(roleTargetUrlMap.containsKey(authorityName)) {
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { return roleTargetUrlMap.get(authorityName);
isAdmin = true;
break;
} }
} }
if (isUser) { throw new IllegalStateException();
return "/homepage.html";
} else if (isAdmin) {
return "/console.html";
} else {
throw new IllegalStateException();
}
} }
/** /**
@ -83,12 +80,4 @@ public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSu
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
} }
public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
} }

View File

@ -0,0 +1,32 @@
package org.baeldung.spring;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.*;
@Service
public class MyUserDetailsService implements UserDetailsService {
private Map<String, User> roles = new HashMap<>();
@PostConstruct
public void init() {
roles.put("admin", new User("admin", "{noop}admin1", getAuthority("ROLE_ADMIN")));
roles.put("user", new User("user", "{noop}user1", getAuthority("ROLE_USER")));
}
@Override
public UserDetails loadUserByUsername(String username) {
return roles.get(username);
}
private List<GrantedAuthority> getAuthority(String role) {
return Collections.singletonList(new SimpleGrantedAuthority(role));
}
}

View File

@ -1,11 +1,9 @@
package org.baeldung.spring; package org.baeldung.spring;
import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler; import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@ -26,39 +24,30 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
return super.authenticationManagerBean(); return super.authenticationManagerBean();
} }
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.inMemoryAuthentication()
.withUser("user1").password("{noop}user1Pass").roles("USER")
.and()
.withUser("admin1").password("{noop}admin1Pass").roles("ADMIN");
// @formatter:on
}
@Override @Override
protected void configure(final HttpSecurity http) throws Exception { protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off // @formatter:off
http.authorizeRequests() http
.antMatchers("/anonymous*").anonymous() .authorizeRequests()
.antMatchers("/login*").permitAll() .antMatchers("/anonymous*").anonymous()
.anyRequest().authenticated() .antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and() .and()
.formLogin() .formLogin()
.loginPage("/login.html") .loginPage("/login.html")
.loginProcessingUrl("/login") .loginProcessingUrl("/login")
.successHandler(myAuthenticationSuccessHandler()) .successHandler(myAuthenticationSuccessHandler())
.failureUrl("/login.html?error=true") .failureUrl("/login.html?error=true")
.and() .and()
.logout().deleteCookies("JSESSIONID") .logout().deleteCookies("JSESSIONID")
.and() .and()
.rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400) .rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)
.and() .and()
.csrf().disable() .csrf().disable()
; ;
// @formatter:on // @formatter:on
} }