Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Lesson07-UsernamePasswordAuthenticationFilter.pdf
1. • Java uses the filter
“UsernamePasswordAuthenticationFilter”
by default for the URL/login
Lesson 07 Security Application:
UsernamePasswordAuthenticationFilter
public class UsernamePasswordAuthenticationFilter
extends AbstractAuthenticationProcessingFil ter
Processes an authentication form submission. Called Aut henticationPr oces singFilte r prior to Spring Security 3.0.
Login forms must present two parameters to this filter: a username and password. The default parameter names to use are
contained in the static fields SPRI NG_SECURITY_FORM_ USERNAME_KEY and SPRING_SECURITY_FORM_PASSW
ORD_KEY. The
parameter names can also be changed by setting the usernam
ePa r am
eter and passwordPa r am
eter properties.
This filter by default responds to the URL /login.
Since:
3.0
2. 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 userN
otFoundEncodedPassword;
private UserDetailsService user DetailsServi ce;
~ private UserDetailsPasswordService user DetailsPasswordService;
~ublic DaoAuthenticationProvider () {
/ }
setPasswordEncoder( PasswordEncoderFactories . createDelegatingPasswordEncoder());
public final class FormLoginConfigurer<H extends HttpSecurit yBuilder<H» extends
asswordAuthenticationFilter> { I
---------------- -----.
,.. public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter { I
* Creates a new instance public static final String SPRING_ SECURITY_FORM_USERNAJ'1E_KEY = "usern ame" ;
• @see HttpSecurity#formLogin()
Mt-•
•...--------------------------------~::::a,.--"" public static final String SPRING_SECURITY_ FORM_ PASSWORD_KEY = "password" ;
.,,,,,,,-
public FormLoginConfigurer() {
~uper (new UsernamePasswordAuthenticationFilter(), null);
llsernameParameter( "username"};
passwordParameter( "pas sword" );
private static final AntPathRequestMatcher DEFAULT_ANT_pATH_REQUESTjlATCHER = new AntPathRequestMatcher( "/ logi n",
"PO
ST");
private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_ KEY;
private String passwordParamet er = SPRING_SECURITY_FORM_ PASSWORD_KEY;
private bool ean post Only = true;
;l t' public UsernamePasswordAuthenticationFilter() {
super (DEFAUL T_ANT_PATH_REQUEST_MATCHER);
I
;l publ ic UsernamePasswordAuthenticationFilter (AuthenticationM
anager authenticationM
anager ) {
super ( DEFAUL T_ANT_ PATH_ REQUEST_ MATCHER , authenticationM
anager );
3. 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
UsernamePasswordAuthenticationFilter
http://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
@
EnableWebsecurity
public class WebSecurit pter {
ana erBuilder auth throws Exce tion
.userOetailsService(secureusercredentialService)
. pas swordEncoder( pa sswordEncode~
verride ~ -
protected void configure(Httpsecurity http) throws Exception
p
.authorizeRequests ()
.ant Matchers( "/", "/ home", "/ register" ). permitAl l()
.anyRequest () .authenticated()
. and()
. formlogin()
. loginPage( "/ l ogi n" )
.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.
@
Autowi red
private UserRepository userRepository;
// Stitching the password encoder to this service instance . . .
@
Autowired
private PasswordEncoder passwordEncoder;
// NOTE : This method i s 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(),
getAuthorities ()) ;
// NOTE : User Details is an interface .
public 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<SimpleGrantedAuthority> authlist = new Arraylist<>() ;
authlist .add( new SimpleGrantedAuthority( "ROLE_USER"));
return authlist ;
Ipackage edu.cpcc.labs.secureaccess.controller;
SecureAccessController.java
p1ckag• edu. cpcc .labs. secure.1ccess. controller;
i111pOrt org. springfra111ework. beans. f ac tory. annotation.Aut owi red;Q
,Controller
public: c:l ■ ss SecureAccessController {
JI Stitching the hilnder to the controller.
~ut owired
private secureAccessHandler handl er;
ti(ietKipping("/")
public StringgetHollePage(){
return •hoate•;
ti(ietKippi ng("/secure")
public String getSecurePage() {
) ' " " ' " ' " ' " ' ' ' ; ~ i
- - - - - ~
ti(ietMapping("/logln")
:ubl!:t~~~i ~~o:!~~;ginPage() { ~ - - - - - - - - - - - - - ~
ti(ietKipping("/register " )
public St ringgetRegisterPage(){
return "regh ter";
// NOTE: In Spring MVC, t he ~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 t he requirement of Htt pServl 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( "/regist er" )
public String createuser(~equestPara111C userna111e" ) String userNaae,
@flequest Param( "password" ) String password,
Model MOdd ) {
// check if this user is already registered . . ..
User founduser • handler .findBy( userNilme );
if ( foundUHr •• null ) {
)
// in this case, resister the user and t ake 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" ;