•Java uses the filter
“UsernamePasswordAuthenticationFilter”
by default for the URL/login
Lesson 07 Security Application:
UsernamePasswordAuthenticationFilter
public class UsernamePasswordAuthenticationFilter
extends AbstractAuthenticationProcessingFilter
Processes an authentication form submission. Called Authen ticationProcessingFilter prior to Spring Security 3.0.
Login forms must present two parameters to this filter: a username and password. T he default parameter names to use are
contai ned in the static fields SPRING_SECU RITY _FORM_USER NAME_KEY and SPRING_SECU RITY _FORM_PASSWORD_KEY. The
parameter names can also be changed by setting the usernameParameter and passwordParameter properties.
This filter by default responds to
the URL /login.
Since:
3.0
FormLoginConfigurer class
UsernamePasswordAuthenticationFilter Class
DaoAuthenticationProvider class
Lesson 07 Security Application: Start-Up Flow
•Java uses the filter
“UsernamePasswordAuthenticationFilter”
by default for the URL/login
public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
J
, ..
* The plaintext password used to perform PasswordEncoder#matches(CharSequence.,
* String)} on when the user is not found to avoid SEC-2056 . . ,
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
private PasswordEncoder passwordEncoder;
, ..
* The password used to perform {@link PasswordEncoder#matches(CharSequence, String)}
* on when the user is not found to avoid SEC-2056. This is necessary, because some
* {@link PasswordEncoder} implementations will short circuit if the password is not
* in a valid format.
*/
private volatile String userNotFoundEnc odedPassword;
private UserDetailsService userDetailsService;
~ private UserDetailsPasswordService userDetailsPasswordService;
~ublic DaoAuthenticationProv ider() {
/}
setPasswordEncoder( PasswordEncoderFactories. createDelegatingPasswordEncoder());
public final class FormLoginConfigurer<H extends HttpSecuri tyBuilder<H» extends
asswordAuthenticationFilter> { I
-----
----------- -----. , ..
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter { I
* Creates a new instance public static final String SPRING_SECURITY_FORM_USERNAJ'1E_KEY = "username";
• @see HttpSecurity#formLogin()
Mt-•• ... --------------------------------~::::a,.--"" public static final String SPRING_SECURITY _FORM_PASSWORD_KEY = "password";
.,,,,,,,-public FormLoginConfigurer() {
~
uper(new UsernamePasswordAuthenticationFilter(), null);
llsernameParameter( "username"};
passwordParameter( "passw ord");
private static final AntPathRequestMatcher DEFAULT_ANT_pATH_REQUESTjlATCHER = new AntPathRequestMatcher( "/logi n",
"POST"
);
private String usernameParameter = SPRING_SECURITY_FORM_USERNAME _KEY;
private String passwordParameter = SPRING_SECURITY_FORM _PASSWORD_KEY ;
private boolean postOnly = true;
;l t' public UsernamePasswordAuthenticationFilter() {
super(DEFAUL T_ANT_PATH_REQUEST_MATCHER); I
;l public UsernamePasswordAuthenticationF il ter(AuthenticationManager authenticationManager) {
super(DEFAUL T_ANT_PATH_REQUEST_MATC HER, authenticationManager);
Method from UserDetails Service
configureGlobal() is passing in a builder that
allows you to build the authentication model.
It builds a service that can pull your
credentials from the database
Filter
UsernamePasswordAuthenticationFilter
When it comes to authentication with
Spring Security, nothing gets called in the
controller. All of it is happening behind
the scenes
The UserDetails is stored in a cookie
and the server stores the cookie in a
session.
When the cookie is alive the server
will know that when you go from the
login page to the secure page the
server will know that you are logged
in (Authenticated+Authorized)
Lesson 07 Security Application
UsernamePasswordAuthenticationFilterhttp://localhost:8080/login
Authentication Manager
Authentication Provider
Where is Provider Manager?
“Traffic Cop”
package edu.cpcc.labs.secureaccess.auth;
WebSecurityConfig.java
pac age e u.cpcc. a s.secureaccess.au ;
)
import org. springframework. beans. factory. annotation. Autowired;O
@Configuration
@EnableWebsecuri ty
public class WebSecuri t pter {
ana erBuilder auth throws Exce tion
. use rOetai lsService ( secureuserc redent ia lService)
. pas swordEncoder( pa sswordEncode~
verride ~ -
protected void configure(Httpsecurity http) throws Exception
p
. authorizeRequests ()
. antMatchers( "/", "/ home", "/register"). permitAll()
. anyRequest () . authenticated()
. and()
. formlogin()
. loginPage(" /login")
.permitAll()
. and()
. logout()
.permitAll();
package edu.cpcc.labs.secureaccess.auth;
SecureUserCredential Service
package edu. cpcc. labs. secureaccess. auth;
Special service class that implements the
UserDetailsService
Added to configuration so each request can
be validated and authenticated.
I'----------'°"" ____ _. security interface.
// NOTE: you can also use omponent or @Repository • in all these cases
// it will create a single l' stance of this class.
// Stitching the user repository to this service instance.
@Autowired
private UserReposi tory userReposi tory;
// Stitching the password encoder to this service instance ...
@A
utowired
private PasswordEncoder passw ordEncoder;
// NOTE: This method is called by the Spdng sr-------------,
// This method looks up the user using JPA at
@Override I"-----------~
public 1userDetai13 loadUserByUsername(String username) {
User
user = user eposi ory. in y sername username ;
if (user == null) {
throw new UsernameNotFoundException(username);
}
return new org. springframework. security. core. userdetails. User(user. getUsername(),
user. getPassword(),
getAuthori ties());
// NOTE: User Details is an interface.
pu
blic UserDetails registerUser(User newUser)
/ /
NOTE: an instance of password encoder is used to encrypt the
// password when it is stored in the database ...
newUser.
setPassword(passwordEncoder. encode(newUser. getPassword()));
User savedUser = userRepository.save(newUser);
// NOTE: the spring security User class implements a UserOetails interface .
return new org. springframework. security. cor-e. userdetails. User(savedUser. getUsername(),
savedUser. getPassword(),
getAuthorities() );
// NOTE: Typically this method should query a database and return
// the ACL -access level list.
private List<SimpleGrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthori ty> authlist = new Arraylist<>();
authlist. add(new SimpleGrantedAuthority( "ROLE_USER"));
return authlist;
I package edu.cpcc.labs.secureaccess.controller;
SecureAccessController.java
p1ckag• edu. cpcc. labs. secure.1ccess. controller;
i111pOrt org. springfra111ework. beans. factory. annotation.Aut owired;Q
,Controller
public: c:l■ss SecureAccessController {
JI Stitching the hilnder to the controller.
~utowired
private secureAccessHandler handl er;
ti(ietKipping(
"/")
publicStringgetHollePage(){
return•hoate•;
ti(ietKipping(
"/secure")
public String getSecurePage() {
) '""'"'"'"'''; ~i -----~
ti(ietMapping( "/logln")
:ubl!:t~~~i~~o:!~~;ginPage() { ~-------------~
ti(ietKipp ing("/register")
publicStringgetRegisterPage(){
return"reghter";
// NOTE: In Spring MVC, the ~equestPara• annoution ls used to read the fo.-.. data and
II bind it aut01Utically to the paraJMter present in the provided 111ethod.
II SO, it ignores the requirement of HttpServl etRequest object to read the provided diltil,
// In this cue, both the user n■IH and password ■re passed in thru the login foMI
@'PostMapping(" /register")
public String createuser(~equestPara111C userna111e") String userNaae,
@flequestPa ram("password") String password,
Model MOdd) {
// check if this user is already registered ....
User foundus er • handler.findBy(userNilme);
if (foundUHr •• null) {
)
// in this case, resister the user and ta ke the11 to the login page., .
handll!r
.createUser(userNil-, password);
return "login";
llH {
// the user is already registered ..•
Syste111.011t.println("User is alrec1dy registered .. ");
IIOdel.addAttribute("eichts", tru1);
return"register";