SlideShare a Scribd company logo
1 of 3
Download to read offline
• 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
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 );
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" ;

More Related Content

Similar to Lesson07-UsernamePasswordAuthenticationFilter.pdf

Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityWashington Botelho
 
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013Michelangelo van Dam
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flaskJeetendra singh
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio
 
Creating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdfCreating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdfShaiAlmog1
 
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QACreating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QAarchwisp
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
The hidden gems of Spring Security
The hidden gems of Spring SecurityThe hidden gems of Spring Security
The hidden gems of Spring SecurityMassimiliano Dessì
 
Securing Portlets With Spring Security
Securing Portlets With Spring SecuritySecuring Portlets With Spring Security
Securing Portlets With Spring SecurityJohn Lewis
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptPatiento Del Mar
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQUA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQMichelangelo van Dam
 
Integrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsIntegrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsDan Wahlin
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...appsec
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013Michelangelo van Dam
 
Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기JeongHun Byeon
 

Similar to Lesson07-UsernamePasswordAuthenticationFilter.pdf (20)

Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
UA testing with Selenium and PHPUnit - TrueNorthPHP 2013
 
Build restful ap is with python and flask
Build restful ap is with python and flaskBuild restful ap is with python and flask
Build restful ap is with python and flask
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel Controllers
 
Creating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdfCreating a Facebook Clone - Part XLV.pdf
Creating a Facebook Clone - Part XLV.pdf
 
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QACreating "Secure" PHP Applications, Part 1, Explicit Code & QA
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 
The hidden gems of Spring Security
The hidden gems of Spring SecurityThe hidden gems of Spring Security
The hidden gems of Spring Security
 
Securing Portlets With Spring Security
Securing Portlets With Spring SecuritySecuring Portlets With Spring Security
Securing Portlets With Spring Security
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Thymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.pptThymeleaf and Spring Controllers.ppt
Thymeleaf and Spring Controllers.ppt
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQUA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
 
Integrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight ApplicationsIntegrating Security Roles into Microsoft Silverlight Applications
Integrating Security Roles into Microsoft Silverlight Applications
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013UA testing with Selenium and PHPUnit - PFCongres 2013
UA testing with Selenium and PHPUnit - PFCongres 2013
 
ERRest
ERRestERRest
ERRest
 
Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기
 

Recently uploaded

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
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" ;