Passing atributes to the view in a Spring Security application - java

In my spring application, the login process is handled by spring security using the UserDetailsService and BCryptPassword classes. When the login is successful, this class redirect the use to the main page:
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
HttpSession session = request.getSession();
SavedRequest savedReq = (SavedRequest) session.getAttribute(WebAttributes.ACCESS_DENIED_403);
if (savedReq == null) {
response.sendRedirect(request.getContextPath() + "/acesso/home");
}
else {
response.sendRedirect(request.getContextPath() + "/acesso/login?erro=no_permit");
}
}
}
In the jsp page, I can get the username using this expression:
${pageContext.request.remoteUser}
But, in my database, I also have stored the first and last name. I need, in the class above (or in any place possible), pass this data to my view. I try this:
request.getSession().setAttribute("username", "Usuario Teste");
using this in the view: ${username}, but when I run the application, nothing is displayed.
Anyone can point me a way to do that?
my spring security configuration
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/resources/**", "/publico/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/acesso/login").permitAll()
.loginProcessingUrl("/login").permitAll()
.usernameParameter("login")
.passwordParameter("senha")
.successHandler(new CustomAuthenticationSuccessHandler())
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(new CustomAccessDeniedHandler())
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/acesso/login").permitAll();
}
UPDATE
Authentication Provider
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Autowired
private UserDetailsService usuario;
#Autowired
private BCryptPasswordEncoder encoder;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails user = usuario.loadUserByUsername(name);
if(encoder.matches(user.getPassword(), password)) {
Authentication auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
return auth;
}
else {
return null;
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
UserDetailsService
#Service
public class AcessoService implements UserDetailsService {
#Autowired
private UsuarioHome accountDao;
#Override
#Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Usuario account = accountDao.findByField("login", username);
if(account==null) {
System.out.println("No such user: " + username);
throw new UsernameNotFoundException("No such user: " + username);
} else if (account.getAutorizacao().isEmpty()) {
System.out.println("User " + username + " has no authorities");
throw new UsernameNotFoundException("User " + username + " has no authorities");
}
List<Permissao> lista = new ArrayList<Permissao>();
int max = account.getAutorizacao().size();
for(int i=0; i<max; i++) {
int max2 = account.getAutorizacao().get(i).getPermissao().size();
for(int j=0; j<max2; j++) {
lista.add(account.getAutorizacao().get(i).getPermissao().get(j));
}
}
boolean accountIsEnabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(account.getLogin(), account.getSenha(), accountIsEnabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(lista));
}
public List<String> getRolesAsList(List<Permissao> list) {
List <String> rolesAsList = new ArrayList<String>();
for(Permissao role : list){
rolesAsList.add(role.getNome());
}
return rolesAsList;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public Collection<? extends GrantedAuthority> getAuthorities(List<Permissao> list) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRolesAsList(list));
return authList;
}
}

Yor are storing your "username" data in session.
You can try to get it in one of this two ways.
request.setAttribute("username", "Usuario Teste"); and then yo can use ${username} EL directly. Or you can use request.getSession().setAttribute("username", "Usuario Teste"); with ${sessionScope.username} EL.
You must to know the differents between session and request scopes.
PD:
Read this.
In another side, to get the username in Spring Sec yo can try to use <sec:authentication property="principal.username" />
And, if you want to use more complex objects than one String as principal, you can extends the UsernamePasswordAuthenticationToken.

Related

Spring Cloud Netflix Zuul routing with account service

I am developing a microservices web application.
I have this microservices:
frontEnd service (all html files)
Account service (with Spring Security)
ZuulGateway service
Demo service (a simple rest controller that return a string)
EurekaServer service
My account service works. The login phase works and the JWT creation works. I save it in the header of the response:
response.addHeader("Authorization", "Bearer " + token);
This is the Ajax code in the frontEnd:
/* sign in submit function */
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({ /* Ajax call to AccountMicroservice for login */
url : 'http://localhost:8762/token/generate-token',
type : "POST",
data : {
username : $("#username").val(),
password : $("#password").val()
},
success : function(data) {
console.log(data.token);
window.location.href = 'http://localhost:8762/test';
},
error : function(result) {
alert("Sign in failed!");
console.log(result);
}
});
});
The problems arose with the addition of Spring Cloud Netflix Zuul. The gateway server port is 8762.
Each request to 'http://localhost:8762/token/generate-token' return a 401 error.
These are the Zuul gateway service. I omitted the import.
application.properties:
server.port=8762
spring.application.name=gateway-service
eureka.client.serviceUrl.defaultZone=${EUREKA_SERVER_URL:http://localhost:8761/eureka}
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
zuul.routes.test-service.path=/test/**
zuul.routes.test-service.service-id=test-service
zuul.routes.account-service.path=/token/**
zuul.routes.account-service.service-id=account-service
zuul.routes.auth-service.sensitive-headers=Cookie,Set-Cookie
webSecurityConfig:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.addFilterAfter(new JwtTokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
// allow all who are accessing "auth" service
.antMatchers(HttpMethod.POST, "/token/**", "/signup").permitAll()
// Any other request must be authenticated
.anyRequest().authenticated();
}
//The CORS filter bean - Configures allowed CORS any (source) to any
//(api route and method) endpoint
#Bean
CorsConfigurationSource corsConfigurationSource() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin(CorsConfiguration.ALL);
//config.addAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return source;
}
}
JwtTokenUtil:
#Component
public class JwtTokenUtil implements Serializable {
public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(SIGNING_KEY)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(Authentication authentication) {
final String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(SignatureAlgorithm.HS256, SIGNING_KEY)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + ACCESS_TOKEN_VALIDITY_SECONDS*1000))
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (
username.equals(userDetails.getUsername())
&& !isTokenExpired(token));
}
UsernamePasswordAuthenticationToken getAuthentication(final String token, final Authentication existingAuth, final UserDetails userDetails) {
final JwtParser jwtParser = Jwts.parser().setSigningKey(SIGNING_KEY);
final Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
final Claims claims = claimsJws.getBody();
final Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
return new UsernamePasswordAuthenticationToken(userDetails, "", authorities);
}
}
JwtTokenAuthenticationFilter:
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
// 1. get the authentication header. Tokens are supposed to be passed in the authentication header
String header = request.getHeader(HEADER_STRING);
String username = null;
String authToken = null;
// 2. validate the header and check the prefix
if (header != null && header.startsWith(TOKEN_PREFIX)) {
// 3. Get the token
authToken = header.replace(TOKEN_PREFIX,"");
try {
username = jwtTokenUtil.getUsernameFromToken(authToken);
System.out.println("\n\n\n\n\n\n\n\n\n\n" + username + "\n\n\n\n\n\n\n\n\n\n");
} catch (IllegalArgumentException e) {
logger.error("c'รจ stato un errore durante il reperimento dello username dal token", e);
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// 4. Validate the token
if (jwtTokenUtil.validateToken(authToken, userDetails)) {
//UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")));
UsernamePasswordAuthenticationToken authentication = jwtTokenUtil.getAuthentication(authToken, SecurityContextHolder.getContext().getAuthentication(), userDetails);
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
logger.info("authenticated user " + username + ", setting security context");
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
// go to the next filter in the filter chain
chain.doFilter(request, response);
}
}
JwtAuthenticationEntryPoint:
#Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
String json = String.format("{\"message\": \"%s\"}", authException.getMessage());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
constants:
public class Constants {
public static final long ACCESS_TOKEN_VALIDITY_SECONDS = 5*60*60;
public static final String SIGNING_KEY = "devglan123r";
public static final String TOKEN_PREFIX = "Bearer ";
public static final String HEADER_STRING = "Authorization";
public static final String AUTHORITIES_KEY = "scopes";
}

Spring Security - UserDetailsService implementation class is not invoked when logging in from angular 4 client

I am securing my spring application with spring security. I have implemented UserDetailService for authenticating user. When logging in from Angular 4, UserDetailService is not invoked and user is not found.
The reason I found is I have not used formLogin() in SecurityConfig.java. For that I have added httpBasic() but its not working. Is there any configurations missing ?
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private LoginUserDetailService loginUserDetailService;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(loginUserDetailService).passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.authorizeRequests()
.antMatchers("/login","/logout", "/home").permitAll()
.anyRequest().fullyAuthenticated().and()
.logout()
.permitAll()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"))
.and()
.httpBasic().and()
.csrf().disable();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
}
Controller
#RequestMapping("/login")
public Principal user(Principal principal) {
logger.info("user logged " + principal);
return principal;
}
LoginUserDetailService
#Service("loginUserDetailService")
public class LoginUserDetailService implements UserDetailsService {
#Autowired
UserRepository userRepository;
#Override
#Transactional
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
System.out.println("Login User Detail Service");
System.out.println("email: "+email);
UserEntity user = userRepository.findByEmail(email);
if (user != null) {
System.out.println("User found ");
}
else {
System.out.println("User not found");
}
Set<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
System.out.println("Authorities of user : " + email);
authorities.forEach(a -> System.out.println(a));
return buildUserForAuthentication(user, authorities);
}
private Set<GrantedAuthority> getUserAuthority(Set<RoleEntity> userRoles) {
System.out.println("Roles: ");
for(RoleEntity role : userRoles) {
System.out.println(role);
}
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (RoleEntity role : userRoles) {
authorities.add(new SimpleGrantedAuthority(role.getRole()));
role.getPermissions().stream().map(p -> new SimpleGrantedAuthority(p.getPermission()))
.forEach(authorities::add);
}
System.out.println("Authorities :");
for(GrantedAuthority authority : authorities)
{
System.out.println(authority);
}
return authorities;
}
private UserDetails buildUserForAuthentication(UserEntity user, Set<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
user.getActive(), true, true, true, authorities);
}
}
Log
2018-10-24 12:45:26.532 INFO 9660 --- [nio-8080-exec-2] c.m.c.AuthenticationController : user logged null
Its solved by passing user credentials in request header of http GET method instead of passing credentials as a body of http POST method from angular client.

Spring Security and SiteMinder integration

I'm trying to integrate SiteMinder with Spring Security. I have a logout button on home page which is supposed to make http get request to backend. I'm trying to invalidate session and redirect back to home page. It's supposed to automatically navigate to log in page which is set up in apache. unfortunate it's not invalidating session or delete cookies.
This is my
WebSecurityConfigurerAdapter
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(ssoHeaderFilter(), RequestHeaderAuthenticationFilter.class)
.authenticationProvider(ssoAuthProvider())
.logout()
.logoutUrl("/logoutPage")
.logoutSuccessUrl("/login?logout")
.deleteCookies("JSESSIONID", "GPSESSION")
.invalidateHttpSession(true)
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**")
.permitAll()
.antMatchers( "/**")
.hasRole("ADMIN");
}
AuthenticationController
#RequestMapping(value="/logoutPage", method = RequestMethod.GET)
public void logoutPage (HttpServletRequest request, HttpServletResponse response) throws ServletException {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
HttpSession session = request.getSession(false);
request.logout();
}
SSOAuthenticationProvider
public class SSOAuthenticationProvider implements AuthenticationProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSSOAuthenticationProvider.class);
public static final Map<UserAuthority, UserAuthority> roleMap = new HashMap<>();
static {
roleMap.put(UserAuthority.ADMIN, UserAuthority.ADMIN);
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UserDetailsBean user = (UserDetailsBean) authentication.getPrincipal();
LOGGER.info("Inside WebSSOAuthenticationProvider authenticate method");
if(isValidRoles(user.getRoles())){
return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(),
getAuthoritiesByRoles( user.getRoles()) );
}
throw new BadCredentialsException(user.getFirstName() + " has not valid roles");
}
private boolean isValidRoles(Set<UserAuthority> roles) {
return roles != null && roles.stream().filter(roleMap::containsKey).findAny().isPresent();
}
#Override
public boolean supports(Class<?> authentication) {
return true;
}
private List<GrantedAuthority> getAuthoritiesByRoles(Set<UserAuthority> roles) {
List<GrantedAuthority> authorities = roles.stream().map(v -> v.name()).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
return authorities;
}
SSOAuthenticationFilter
public class SSOAuthenticationFilter extends RequestHeaderAuthenticationFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SSOAuthenticationFilter.class);
#Value("${project.ui.test.mode:false}")
private boolean guiTestMode;
private String FIRST_NAME = "sso-givenname";
private String LAST_NAME = "sso_surname";
#Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
LOGGER.debug("Working in the test mode for logging");
Enumeration<String> names = request.getHeaderNames();
LOGGER.info("Going to print all http headers");
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getHeader(name);
LOGGER.info("name: " + name + ", value: " + value);
}
UserDetailsBean user = new UserDetailsBean();
if(isTestMode()){
user.setFirstName("Mock");
user.setLastName("User");
user.setRoles(new HashSet<UserAuthority>(Arrays.asList(UserAuthority.ROLE_P_AND_S)));
request.getSession().setAttribute("user" , user);
return user;
}
user.setFirstName(request.getHeader(FIRST_NAME));
user.setLastName(request.getHeader(LAST_NAME));
user.setRoles(new HashSet<UserAuthority>(Arrays.asList(UserAuthority.ROLE_P_AND_S)));
request.getSession().setAttribute("user" , user);
return user;
}
private boolean isTestMode() {
return guiTestMode;
}
}

how can I create a session on spring security from the backend?

I have my spring app with a login with spring security, it works fine, but I want to do something additional.
There are some users that will be logged throught another method, so, I will get a post with the data at my controllers... is there any way from that controller simulate that the user is actually entering his user/password at the login form and then create a session on spring security?
Right now I have this
Spring Securit Configuration
#Autowired
private UserDetailsService customUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/auth/**").authenticated();
http.
authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/admin/**")
.access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/**")
.access("hasRole('ROLE_USER')")
.and()
.formLogin()
.defaultSuccessUrl("/usuario/home")
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/")
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
if(encoder == null) {
encoder = new BCryptPasswordEncoder();
}
return encoder;
}
Login method at my controller (nothing much really..)
#RequestMapping("/login")
public ModelAndView login() {
ModelAndView mvc = new ModelAndView();
mvc.setViewName("login");
mvc.addObject("message", "");
return mvc;
}
I have my details service as well , like this
#Autowired
private UserRepository userRepository;
#Transactional(readOnly=true)
#Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
com.jp.base.domain.User user = userRepository.findByUsername(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());
System.out.println("user roles: " + user.getUserRoles());
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(com.jp.base.domain.User user,
List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
return new ArrayList<GrantedAuthority>(setAuths);
}
}
Any idea how to do this??
Thanks.
There is a way to do that. You can utilize Spring SecurityContextHolder. It would look something like this:
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(principal, credentials);
SecurityContextHolder.getContext().setAuthentication(authentication);
where principal is UserDetails object. If you don't have credentials, you can just pass null.
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_USER");
grantedAuthorities.add(ga);
Authentication auth = new UsernamePasswordAuthenticationToken(user.getUid(), "", grantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(auth);

spring security every url is a blank page

Here's my security config :
#Configuration
#EnableWebSecurity
#ComponentScan("lt.nortal.lab.web.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider authenticationProvider;
#Override
public void configure(final WebSecurity web) throws Exception {
// Allow static resources to be served
web.ignoring().antMatchers("/css**", "/js**", "/html**", "/bootstrap");
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf()
.and()
.authorizeRequests()
.antMatchers("/admin**").hasAuthority("admin") // allow public pages
.antMatchers("/login**").permitAll()
.anyRequest().authenticated() // other pages - authenticated only
.and()
.formLogin() // generate login form
.loginPage("/login")
.permitAll() // permit all to access login form (logical)
.and()
.logout().logoutSuccessUrl("/").permitAll(); // Permit all to access logout url
// (logical)
}
#Override
protected void registerAuthentication(final AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
}
Here's my authetntication provider :
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Autowired
private LoginService loginService;
#Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
String email = authentication.getName();
String pass = (String) authentication.getCredentials();
User user = loginService.login(email);
if (user == null) {
throw new BadCredentialsException("Invalid email.");
}
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("user"));
if (user.getRole() == Role.ADMIN) {
authorities.add(new SimpleGrantedAuthority("admin"));
}
return new CustomAuthenticationToken(new AuthenticatedUser(user.getId(), user.getEmail()),
authorities);
}
#Override
public boolean supports(final Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.equals(authentication);
}
}
login controller:
#Controller
public class LoginLogoutController {
private static final Logger log = LoggerFactory.getLogger(LoginLogoutController.class);
#Autowired
private CurrentUser currentUser;
#Autowired
private LoginService loginService;
/**
* Represents user login form.
*
*/
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(final ModelMap model) {
// add login form attribute
model.put("loginForm", new LoginForm());
return "login";
}
/**
* Processes login form.
*
*/
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String processLogin(
final ModelMap model,
final #Valid #ModelAttribute("loginForm") LoginForm loginForm,
final BindingResult bindingResult) {
User user = null;
// lets check for errors
if (!bindingResult.hasErrors()) {
// no errors, lets try to login user.
user = loginService.login(loginForm.getEmail());
if (user == null) {
// something has failed, reject it with a global errror.
bindingResult.reject("login-generic-fail");
}
}
// at this point, we should have a user. If no user - return same login form.
if (user == null) {
return "login";
}
return "redirect:/";
}
}
When I start the server and go to any page I get a blank page, empty html file. I cant seem to figure out whats wrong here. If you need anything else please let me know

Categories

Resources