Java tutorial
/* * * Springstrap * * @author Jan Philipp Knller <info@pksoftware.de> * * Homepage: http://ui5strap.com/springstrap * * Copyright (c) 2013-2014 Jan Philipp Knller <info@pksoftware.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Released under Apache2 license: http://www.apache.org/licenses/LICENSE-2.0.txt * */ package de.pksoftware.springstrap.basic.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.*; import org.springframework.stereotype.Service; import de.pksoftware.springstrap.core.domain.IAccount; import de.pksoftware.springstrap.core.exception.NoSuchAccountException; import de.pksoftware.springstrap.core.service.IAccountService; @Service public class BasicUserDetailsService implements UserDetailsService { @Autowired private IAccountService storeAccountService; @Autowired private AuthenticationManager authenticationManager; /** * Performs an auto login after signup. * @param newAccount * @param password */ public void autoLogin(IAccount newAccount, String password) { UserDetails userDetails = loadUserByUsername(newAccount.getUsername()); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()); authenticationManager.authenticate(auth); if (auth.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(auth); } } /** * Loads the UserDetails by username */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { IAccount account; try { account = storeAccountService.loadAccountByUsernameOrEmail(username); } catch (NoSuchAccountException e) { throw new UsernameNotFoundException("Neither email nor username have been found!"); } return account; } }