Inside Controller or Filter
@Autowired MyAuthenticationManager myAuthenticationManager;
//AUTHENTICATE
Authentication enteredAuth = new UsernamePasswordAuthenticationToken(enteredUsername, enteredPassword);
Authentication returnedAuth = myAuthenticationManager.authenticate(enteredAuth);
//STORE AUTHENTICATION INTO CONTEXT (SESSION)
SecurityContextHolder.getContext().setAuthentication(returnedAuth);
MyAuthenticationManager.java
@Component
public class MyAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication enteredAuthentication) {
//HARD CODED USER
String username = "myuser";
String password = "mypassword";
String role = "ROLE_USER";
//GET ENTERED CREDENTIALS
String enteredUsername = (String) enteredAuthentication.getPrincipal(); //USERNAME
String enteredPassword = (String) enteredAuthentication.getCredentials(); //PASSWORD
//AUTHENTICATE USER
if (!enteredUsername.equals(username)) { System.out.println("Username not found"); return null; }
if (!enteredPassword.equals(password)) { System.out.println("Incorrect Password"); return null; }
//CREATE AUTHORITIES
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(role));
//CREATE VALIDATED AUTHENTICATION
Authentication validatedAuthentication = new
UsernamePasswordAuthenticationToken(username,password,authorities);
//RETURN VALIDATES AUTHENTICATION
return validatedAuthentication;
}
}