SlideShare a Scribd company logo
Lesson 07 Spring Security Login Code
Execution Path Lesson 07 Spring Security Project
By: Scott Michael Anderson
Date: 12/06/2021
V lesson-seven-spring-security [boot] [devtools]
v II edu.cpcc.labs.secureaccess
> J LessonSevenSpringSecurityApplication.java
v II edu.cpcc.labs.secureaccess.auth
> J SecureUserCredentialService.java
> J WebSecurityConfigJava
v II edu.cpcc.labs.secureaccess.controller
> J SecureAccessControllerJava
> J SecureAccessHandlerJava
v II edu.cpcc.labs.secureaccess.dao
> JOUserRepository.java
v II edu.cpcc.labs.secureaccess.model
> J UserJava
••
> ~ src/main/resources
••
> ~ src/test/java
> ~ JRE System Library [JavaSE-1 .8]
> ~ Maven Dependencies
> l;, src
II, target
~ HELP.md
= mvnw
~ mvnw.cmd
= PLEASE README !!!
ID pom.xml
FormLoginConfigurer class
UsernamePasswordAuthenticationFilter Class
DaoAuthenticationProvider class
Lesson 07 Spring Security
Application: Start-Up
Code Execution Path
• Java uses the filter
“UsernamePasswordAuthenticationFilter” by default
for the URL/login
• Note: The Application Start-Up Code Execution Path
does not include every class/interface/method etc..
executed during the Application Start-Up.
public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
,..
* The plaintext password used to perform Passw
ordEncoder#matches (CharSequence,
* String)} on when the user i s not found to avoid SEC-20S6 .
•1
private static final String USER_NOT_FOUND_PASSWORD ; "userNot FoundPassword";
private PasswordEncoder passwordEncoder;
,..
* The password used to perform {@
link PasswordEncoder#matches ( CharSequence, String)}
* on when the user is not found to avoid SEC- 20S6. This is necessary, because some
* {@link PasswordEncoder} implementations will short circuit if the password is not
* in a valid format.
*/
private volatile String userNotfoundEncodedPassword;
private UserDetailsService userDetai lsSer vi ce;
t private UserDetailsPasswordService userDetailsPasswordService;
D ~ublic DaoAuthenticationProvider() {
/ }
setPasswordEncoder( Passw
ordEncoderFactories . cr eateDeLegatingPasswordEncoder( )) ;
I
public final class FormLoginConfigurer<H extends HttpSecurit yBuilder<H>> extends
public FormLoginConfigurer( ) {
l,uper (new UsernamePasswordAuthenticationFilter(), null ) ;
UsernameParameter( "username" );
passwordParameter( "pas sword " );
private static final AntPathRequestM
atcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestM
atcher ("/ login" ,
"POST" );
private String usernameParameter = SPRING_SECURITY_FORM_ USERNAME_KEY;
private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
private boolean postOnly = true;
~ public UsernamePasswordAuthenticationFilter() {
super (OEFAULT_ANT_PATH_REQUEST_MATCHER ) ;
I
:) public UsernamePasswordAuthenticationFilter(AuthenticationM
anager authenticationM
anager) {
super(DEFAULT_ANT_PATH_REQUEST_MA TCHER , authent icationM
anager ) ;
• 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 Aut henticationProcessingFilter prior to Spring Security 3.0.
Login fonns must present two parameters to this filter: a username and password. The default parameter names to use are
contained in the static fields SPRING_SECURITY_FORM_USERNAME_KEY and SPRING_SECURITY_FORM_PASSWORD_KEY. The
paraineter names can also be changed b setting the use rnam
eParam
eter and passwor dPa r am
eter prope1ties.
!This filter by default responds to the URL / logi n.
Since:
Lesson 07 Spring Security
UsernamePasswordAuthenticationFilter
• We will use the “UsernamePasswordAuthenticationFilter”
to authenticate the user at URL : “http://localhost:8080/login”
UsernamePasswordAuthenticationFilter
UsernamePasswordAuthentication Filter - Tries to find a
username/password request parameter/POST body and if found,
tries to authenticate the user with those values
Spring's FilterChain:
Browser HTTP Request ecu, ltyContextPer lstencefllter
srtfllter Logoutfllt r
OetaultloglnPag G neratlngfllter OefaultlogoulPageGen ratlngfllter
urlty ont xtHold rAw reR qu Anonymou Auth ntl tlonfllt r
lonM nagementfllt r Exception ran latlonfllter Fllle, ecuritylnt I ceptor
your @RestController/ Controller
Marco Behler Notes
Lesson 07 Security Application
DaoAuthenticationProvider
• “DaoAuthenticationProvider” – An AuthenticationProvider that
retrieves user details from the UserDetailsService
User Details Service serves as a hook to source custom credentials
Filte~ uth nt c te(Authentlcat on uth)
Authent·cation
fals
SecureUserCredenfa:
tService Class
DaoAuthenticationProvider Class
Lesson 07 Spring Security Login Code
Execution Path
• The following slides show a high level
overview of the code execution path for
Lesson 07 Spring Security Code “/login”
• Note: Lesson 07 Spring Security “/login”
Code Execution Path does not include
every class/interface/method etc..
executed during the “/login” process
• We will include the Lesson 07 Spring
Security Code Modules, the
UsernamePasswordAuthenticationFilter,
and the DaoAuthenticationProvider
Lesson 07 Spring Security Project
V lesson-seven-spring-security [boot] [devtools]
v II edu.cpcc.labs.secureaccess
> J LessonSevenSpringSecurityApplicationJava
v II edu.cpcc.labs.secureaccess.auth
> J SecureUserCredentialService.java
> J WebSecurityConfigJava
v II edu.cpcc.labs.secureaccess.controller
> J SecureAccessController.java
> J SecureAccessHandler.java
v II edu.cpcc.labs.secureaccess.dao
> J8 UserRepositoryJava
v II edu.cpcc.labs.secureaccess.model
> J User.java
••
> ~ src/main/resources
••
> ~ src/test/java
> IIJ JRE System Library [JavaSE-1.8]
> IIJ Maven Dependencies
> ~ src
~ target
~ HELP.md
mvnw
l!J mvnw.cmd
= PLEASE README !!!
f.J pom.xml
#1
0 Spring Security Example X +
C 0 localhost:8080/login
... Apps @ Dashboard - Centra... 0 Scrublands
Home
Secure
Logm
Register
Login:
User ame:
Password: ,--J---------"l!!I
ISign In I
package edu.cpcc.labs.secureaccess.controller;
SecureAccessController.java
package edu.cpcc.labs.secureaccess.controller;
import org.springframework.beans.factory.annotation.Autowired;O
@
Controller
public class SecureAccessController {
II Stitching the hander to the controller .
@Autowired
private SecureAccessHandler handl er;
@GetMapping("/" )
public String getHomePage() {
return "home" ;
}
@GetMapping("lsecure" )
public String getsecurePage() {
return 11
secure11
;
}
@GetMapping("llogin" )
public String getLoginPage() {
return "login";
}
@GetMapping("lregister" )
public String getRegisterPage() {
return "register" ;
}
II NOTE: In Spring MVC, the @
RequestParam annotation is used to read the form data and
II bind it automatically to the parameter present in the provided method.
II So, it ignores the requirement of HttpServletRequest obj ect to read the provided data.
II In this case, both the user name and password are passed in thru the login form
@
PostMapping("lregister" )
public String createUser(@
RequestParam("username" ) String userNam
e,
@RequestParam("password" ) String password,
Model model ) {
}
II check if this user is already registered . ...
User foundUse r = handler .findBy( userName );
if (foundUser == null ) {
}
II in this case, register the user and take them to the login page .. .
handler . createUser( userN
ame, password );
return "login" ;
else {
}
II the user is already registered ...
System. out.println( "User is already registered . .. ");
model .addAttribute( "exists" , true);
return "register" ;
UsernamePasswordAuthenticationFilter Class
#2
J UsernamePasswordAuthenticationFilter.class ~
58
59
60
61
62
•630
64
65
66
•670
68
69
70
I710
72
t 73
;z.
.,
•l'-
~ 74
-~
i 75
I
76
77
"·
78
~~: 79
m80
ij 81
I
I 82
I83
.
,
84
B85
•86
private String passw
ordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
private boolean postOnly = true;
public UsernamePassw
ordAuthenticationFilter() {
super(DEFAULT_ANT_PATH_REQUEST_MATCHER );
}
public UsernamePassw
ordAuthenticationFilter(AuthenticationM
anager authenticationManager ) {
super (DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
}
if (this . postOnly && !request .getMethod() .equals( "POST" )) {
throw new AuthenticationServiceException( "Authentication method not supported: 11
+ request .getM
ethod());
J
String username = obtainUsername( request );
username = (usernam
e != null ) ? username : "";
username = username .trim();
String password = obtainPassw
ord( request );
password = (password != null ) ? password : "" ;
UsernamePassw
ordAuthenticationToken authRequest = new UsernamePassw
ordAuthenticationToken( username, password );
// Allow subclasses to set the "details" property
setDetails( request, authRequest );
return this .getAuthenticationM
anager().authenticate( authRequest );
DaoAuthenticationProvider Class
#3
J DaoAuthenticationProvider.java ~
77 this . logger.debug( "Failed to authenticate since password does not match stored value" );
78 throw new BadCredentialsException(this .messages
79 .getM
essage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials'' ));
80
81
82
830
84
85
86
87
-
::~ 880
89
90
..
'•
91
92
93
94
95
96
97
.. 98
99
~ 100
.101
· 102
❖
'•103
. 104
·: 105
,• 106
_
§107
108
'·109
. 110
111
}
}
@
Override
protected void doAfterPropertiesSet() {
Assert . notNull(this .userDetailsService, "A UserDetailsService must be set" );
}
@
Override
protected final UserDetails retrieveUser(String username, UsernamePassw
ordAuthenticationToken authentication)
throws AuthenticationException {
}
prepareTimingAttackProtection();
try t
}
UserDetails loadedUser =this .getUserDetailsService().loadUserByUsername(username);
if (loadedUser == null ) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation" );
}
return loadedUser;
catch (UsernameN
otFoundException ex) {
mitigateAgainstTimingAttack(authentication);
throw ex;
}
catch (InternalAuthenticationServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new InternalAuthenticationServi~eException (ex.getM
essage(), ex ) ;
}
(t org.springframework.security.authentication.lnternalAuthenticationServiceException
DaoAuthenticationProvider Class
#4
J DaoAuthenticationProviderJava ~
1120 verride
113 protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
114 UserDetails user) {
115 boolean upgradeEncoding = this .userDetailsPasswordService != null
116 && this .passw
ordEncoder . upgradeEncoding(user.getPassword());
117 if (upgradeEncoding) {
118 String presentedPassword = authentication.getCredentials().toString();
119 String newPassword = this .passwordEncoder.encode(presentedPassword);
120 user= this .userDetailsPasswordService.updatePassword(user, newPassword);
121
122
123
124
1250
126
127
128
129
130
1310
132
133
134
135
136
137
1380
139
140
141
142
143
144
1450
146
147
148
149
150
1510
152
153
154
1550
156
157
158
1
1590
160
161
}
return super . createSuccessAuthentication(principal, authentication, user);
}
private void prepareTimingAttackProtection() {
if (this .userNotFoundEncodedPassword == null ) {
this .userNotFoundEncodedPassword = this .passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
}
}
private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
if (authentication.getCredentials() != null) {
}
}
String presentedPassword = authentication.getCredentials().toString();
this .passwordEncoder.matches(presentedPassword, this .userNotFoundEncodedPassword);
/**
* Sets the PasswordEncoder instance to be used to encode and validate passw
ords . If
* not set, the password will be compared using
* {@
link Passw
ordEncoderFactor ies#createDelegatingPassw
ordEncoder() }
* @param passw
ordEncoder m
ust be an instance of one of the {@
code PasswordEncoder}
* t ypes .
*/
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null" );
this . passwordEncoder = passwordEncoder;
this .userNotFoundEncodedPassword = null;
}
protected PasswordEncoder getPasswordEncoder() {
return this .passwordEncoder;
}
public void setUserDetailsService(UserDetailsService userDetailsService) {
this .userDetailsService = userDetailsService;
}
protected UserDetailsService getUserDetailsService() {
return this .userDetailsService;
}
1h? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - •
SecureUserCredentialServices Class
#5
J SecureUserCredentialService.java ~
1 package edu.cpcc.labs.secureaccess .auth;
2
30 import java. util .Arraylist;Q
16
17 // N
OTE: the UserDetailsService is spring secur ity interface .
18 // N
OTE: you can also use @
Component or @
Repository - in all these cases it will create a single i
190 / *
20 * N
ote : N
ever name your class after a technical stack
21 * the previous class name was "MySQLUserDetailsService" - we changed it to "SecureUserCredential
22
23
24
• 25
26
27
280
29
30
31
320
; 33
34
*/
@Service
public class SecureUserCredentialService implements UserDetailsService {
// Stitching the user repository to this service instance ...
/ *
* Uses dependency injection to instantiate a class instance of that interface
*
*/
@Autowired
private UserRepository userRepository;
35 // Stitching the passw
ord encoder to this service i nstance . . .
36
370 / *
38 * Uses dependency injecti on to instantiate a cl ass instance of that interface
39 */
40
410 @Autowired
42 private PasswordEncoder passw
ordEncoder;
43
44
45
46
470
48
49
50
51
52
53
540
55
56
57
58
59
60
61
62
63
""""
// N
OTE: This method is called by the Spring Securi t y AuthenticationProvider
// This method looks up the user using JPA at the time of authentication.
/ *
* "loadUserByUsername" method is used to find out if the "username" exist in
* the+
*
*
*/
@Override
public UserDetails loadUserByUsername(String username ) {
User user = userRepository .findByUsername( username );
}
'*
i~ t user == nuLL J t
throw new UsernameNotFoundException( username );
}
return new org . springframew
ork. security .core . userdetails . User (user .getUsername() ,
user .getPassw
ord ( ),
getAuthorities ());
#6
package edu.cpcc.labs.secureaccess.dao;
interface UserRepository.java
package edu.cpcc.labs.secureaccess.dao;
import org.springframework.data.jpa.repository.JpaRepository;
@Repository
public interface UserRepository extends JpaRepository<User, Long>
User findByUsername(String userName );
}
{
SecureUserCredentialServices Class
#7 J SecureUserCredentialService.java ~
1 package edu.cpcc . labs . secureaccess.auth;
2
30 import java.util.Arraylist;Q
16
17 // NOTE: the UserDetailsService is spring security interface.
18 / / NOTE: you can also use @
Component or @
Repository - in all these cases it will create a single i
190 / *
20 * Note: Never name your class after a technical stack
21 * the previous class name w
as "MySQLUserDetailsService" - we changed it to "SecureUserCredential
22 */
23
24 @
Service
t 25 public class SecureUserCredentialService implements UserDetailsService {
26
27
280
29
30
31
320
, 33
34
35
36
370
38
39
40
410
42
43
44
45
46
470
48
49
50
51
52
53
540
55
56
57
58
59
60
61
62
63
C:IIA
// Stitching the user repository to this service instance ...
/ *
* Uses dependency injection to instantiate a class instance of that interface
*
*/
@
Autowi red
private UserRepository userRepository;
// Stitching the password encoder to this service instance .. .
/ *
* Uses dependency injection to instantiate a class instance of that interface
*/
@
Autowired
private PasswordEncoder passw
ordEncoder;
// NOTE: This method is called by the Spring Security AuthenticationProvider
// This method looks up the user using JPA at the time of authentication.
/ *
* "loadUserByUsername" method is used to find out if the "username " exist in
* the+
*
*
*/
@Override
public UserDetails loadUserByUsername(String usernam
e) {
User user = userRepository .findByUsername( usernam
e);
if (user == null ) {
throw new UsernameNotFoundException( usernam
e);
}
return new org.spr1ngTrameworK.secur1ty.core.useraeta11s.User( user .getUsername(J,
user .getPassword(),
getAuthorities());
User Class
#8
J UserJava ~
1 package edu.cpcc.labs.secureaccess.model;
2
3
4
import javax.persistence. *;
5 @Entity
8 6 public class User {
7
80
9
~ 10
11
120
~ 13
14
~ 15
16
f 110
18
19
20
f 210
22
23
24
.250
~ 26 I
121
28
f 290
30
31
32
f 330
34
35
36
. 370
38
39
40 }
41
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Long id ;
@Column(nullable = false, unique= true )
private String username;
private String password ;
public Long getid() {
return id;
}
public void setid(Long id ) {
this . id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username ) {
this . username = username;
}
public String getPassword() {
return password ;
}
public void setPassword(String password ) {
this . password = password;
}
User Class
#9
J User.java ~
1 package edu.cpcc.labs.secureaccess.model;
2
3 import javax.persistence. *;
4
5 @Entity
8 6 public class User {
7
80
9
~ 10
11
120
~ 13
14
~ 15
16
. 170
18
19
20
. 210
22
23
24
. 250
26
27
28
. 290
30
31
@Id
@GeneratedValue (strategy = GenerationType. AUTO)
private Long id ;
@Column (nullable = false, unique= true )
private String username;
private String passw
ord;
public Long getid() {
return id;
}
public void setid(Long id ) {
this .id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username ) {
this .username = username;
}
32 - - - - - - - - - - - - - - - - - - - - - - - -
l!!c~
I
35
public String getPassw
ord() {
return passw
ord;
}
36 __________________________,
. 370
38
public void setPassw
ord(String passw
ord ) {
this . passw
ord = passw
ord ;
39 }
40 }
41
SecureUserCredentialServices Class
#10 J SecureU
serCredentialSeNicejava ~
470
48
49
50
51
52
53
540
A 55
• 56
57
• 58
59
• 60
61
62
63
640
65
66
67
68
69
70
71
72
73
74
75
76
77
78
• 790
80
81
82
83
84
85
86
87
88
89
90
91
< 92
930
94
95
960
,· 97
98
" 99
100
101
102 }
/ *
* "loadUserByUsername" method is used to find out if the "username" exist in
* the+
*
*
*/
@Override
public UserDetails loadUserByUsername(String username ) {
User user = userRepository .findByUsername(username );
if (user == null ) {
throw new UsernameNotFoundException( username );
}
return new org.springframework.security.core.userdetails.User( user .getUsername(),
user .getPassword(),
getAuthorities());
}
I*
* registerUser is taking an instance of the "User" and taking the password from
* that user then registerUser is encoding that password (Hashed ) . Passw
ord is
* encoded/ encrypted and then saved into the database
*
* Once that is complete, he calls the UserRepository (the handle to the
* repository ) and calls save passing in the instance of the User .
*
* Then he gives back the UserDetails (an object in Spring)
*
*
*
*I
// NOTE : User Details is an interface.
public UserDetails registerUser(User newUser ) {
}
// NOTE: an instance of passw
ord encoder is used to encrypt the passw
ord when it is stored in the database . ..
newUser .setPassword( passw
ordEncoder .encode( newUser .getPassword()));
User savedUser = userRepository .save( newUser );
// NOTE: the spring security User class implements a UserDetails interface...
return new org.springframew
ork .security.core . userdetails .User( savedU
ser. getUsername( ),
savedUser .getPassword(),
getAuthorities());
// NOTE: Typically this method should query a database and return the ACL - access level list.
/ *
* getAuthorities - provides access levels for users "What can I do"
* ,
private List<SimpleGrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authlist = new Arraylist<>();
authlist .add (new SimpleGrantedAuthority( "ROLE_USER"));
return authlist;
}
SecureUserCredentialServices Class
#11
J SecureUserCredentialServiceJava ~
320 @Autowired
~ 33 private UserRepository userRepository;
34
35
36
370
38
39
40
410
'° 42
✓
43
48
49
50
51
52
53
540
55
56
57
58
59
60
61
62
63
// Stitching the password encoder to this service instance ...
/ *
* Uses dependency injection to instantiate a class instance of that interface
*/
@Autowired
private PasswordEncoder passwordEncoder;
// NOTE: This method is called by the Spring Security AuthenticationProvider
// This method looks up the user using JPA at the time of authentication.
/ *
* "loadUserByUsername" method is used to find out if the "username" exist in
* the+
*
*
*/
@Override
public UserDetails loadUserByUsername(String username ) {
User user = userRepository .findByUsername( username );
if (user == null ) {
throw new UsernameNotFoundException( username );
}
return new org.springframew
ork.security.core.userdetails.User( user .getUsername(),
user .getPassword(),
getAuthorities());
}
DaoAuthenticationProvider Class
#12
J DaoAuthenticationProviderJava ~
32
"
<
330 /**
34 * An {@
link AuthenticationProvider} implementation that retrieves user details from a
* {@
link UserDetailsService} .
35
36
37
38
39
40
41
420
43
44
45
46
47
48
49
500
51
52
53
54
55
56
57
58
59
60
61
620
63
64
65
660
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
*
* @author Ben Alex
* @author Rob Winch
*/
public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
/**
* 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 = "userN
otFoundPassword" ;
private PasswordEncoder passwordEncoder;
/**
* The password used to perform {@l ink 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 f ormat.
*/
private volatile String userNotFoundEncodedPassword;
private UserDetailsService userDetailsService;
private UserDetailsPasswordService userDetailsPasswordService;
public DaoAuthenticationProvider() {
setPasswordEncoder(Passw
ordEncoderFactories.createDelegatingPasswordEncoder( ) );
}
~ verride
@
SuppressWarnings( "deprecation" )
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
if (authentication.getCredentials() == null) {
this .logger .debug( "Failed to authenticate since no credentials provided" );
throw new BadCredentialsException(this .messages
.getM
essage( "AbstractUserDetailsAuthenticationProvider . badCredentials", "Bad credentials"));
}
String presentedPassword = authentication .getCredentials().toString();
if ( !this .passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
this .logger.debug( "Failed to authenticate since password does not match stored value" );
}
throw new BadCredentialsException(this .messages
.getM
essage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials" ));
DaoAuthenticationProvider Class
#13
J DaoAuthenticationProviderJava ~
97 }
98
99
100
101
102
103
104
105
106
107
108
109
110
111
ij1120
-113
::114
·=
11s
:116
~117
..
1 118
-~119
.h20
,.
. ,1121
i122
:;
(§(123
124
}
return loadedUser;
}
catch (UsernameN
otFoundException ex) {
mitigateAgainstTimingAttack(authentication);
throw ex;
}
catch (InternalAuthenticationServiceException ex) {
throw ex;
}
catch (Exception ex) {
throw new InternalAuthenticationServiceException(ex.getM
essage(), ex);
}
verride
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication,
UserDetails user) {
}
boolean upgradeEncoding = this .userDetailsPassw
ordService != null
&& this .passw
ordEncoder.upgradeEncoding(user.getPassword());
if (upgradeEncoding) {
}
String presentedPassword = authentication.getCredentials().toString();
String newPassw
ord = this .passw
ordEncoder.encode(presentedPassword);
user= this .userDetailsPasswordService.updatePassw
ord(user, newPassw
ord);
return super .createSuccessAuthentication(principal, authentication, user);
SecureAccessController Class
#14
J SecureAccessControllerJava ~
1 package edu.cpcc.labs.secureaccess.controller;
2
30 import org.springframework.beans.factory.annotation.Autowired;Q
11
12
8 13
14
15
160
'° 17
✓
18
19
1200
' .
,•· ···21
;, •·22
123
: ·24
25
260
f 27
28
29
30
310
f 32
33
34
35
360
f 37
38
39
40
@Controller
public class SecureAccessController {
I
// Stitching the hander to the controller.
@Autowired
private SecureAccessHandler handler;
@GetMapping ("/" )
public String getHomePage() {
return "home" ;
}
@GetMapping("/secure" )
public String getSecurePage() {
return "secure" ;
}
@GetMapping ("/login" )
public String getloginPage() {
return "login" ;
}
@GetMapping ("/register" )
public String getRegisterPage() {
return "register" ;
}
1e txecut1on Patn
UsernamePasswordAuthenticationFilter
package edu.cpcc.la s.secureaccess.controller;
SecureAcce sController.java
package edu. cpcc. labs. secureaccess. co roller;
import org .springframework. beans . f ac ry.annotation. Autowired;O
~ontroller
public class SecureAccessController
// Stitching t he hander t o the ntroller.
{IAut owired
private secureAccessHandler h ler;
@GetMapping( "/" )
public String get HomePage()
return "home";
@GetMapping( "/secure" )
public String getSecurePag
return "secure";
@GetMapping( "/login" )
public String getLoginPage ()
return "login" ;
// NOTE : In Spring MVC, the @
RequestParam annotation is used to read the form dat a and
/ / bind it automatically to the parameter present in the provided method .
/I So, it ignores the requirement of HttpServletRequest object to read the provided data.
// In this case, both the user name and password are passed in thru the login form
~Post Mapping( ··/register.. )
public Stri ng createUser(, R
equestParam( "username" ) String userName,
f Request Param( "password") String password,
Model model) {
// check if this user is already regist ered . ...
user foundUser • handler .findBy(userName) j
if (founduser •• null) {
}
// in this case, register the user and take them to the login page . . .
handler . createUser(userName, password) ;
return "l ogin" ;
else {
/ / the user is already registered .. .
model. addAtt ribute("edsts" , true );
return "register";
}
DaoAuthenticationProvider
ge edu.cpcc.labs.s th;
•
rv1ce
Special service class that imple ents the
UserDetailsService
Added to configuration so each quest can
be validated and authenticated.
ilsService is spring security interface.
lso use @Component or @
Repository - in all these cases
ea single instance of this class .
SecureUserCredentialService implements UserDetailsService {
itching the user repository to this service instance ...
wired
te UserRepository userRepository;
titching the passw
ord encoder to this service instance .. .
owired
rride
passwordEncoder;
is called by the Spring Security AuthenticationProvider
up the user using JPA at the time of authentication.
lie UserDetails loadUserByUsername(String username) {
org.springframew
ork. security .core.userdetails .User(user .getUsername () ,
user .getPassw
ord () ,
getAuthorities ())·
// N
OTE : User Details is an interface .
public UserDetails registerUser(User new
User) {
// N
OTE : an instance of passw
ord encoder is used to encrypt the
// password when it is stored in the database . . .
newUser .setPassw
ord (passwordEncoder .encode(new
User .getPassword ())) ;
User savedUser = userRepository .save(new
User );
•
// N
OTE: the spring security User class implements a UserOetails inte
return new org .springframew
ork.security.core.userdetails.User(saved
ace .. .
r .getUsername () .
er.getPassw
ord () ,
horities ()) ;
save
get
// NOTE: Typically this method should query a database
// the ACL - access level list.
private 1st< imp e rante ut ority> get ut orities
List<SimpleGrantedAuthority> authlist = new Arraylist<>() ;
authlist .add (new SimpleGrantedAuthority("ROLE_USER")) ;
return authlist;
}
package edu.cpcc.labs.secureaccess.dao;
interface UserRepository.java
package edu.cpcc.labs.secureaccess.dao;
import org.springframework.data.jpa . repository.JpaRepository;
@
Repository
Spring Security Example X +
~ X 0 localhosl8080/login
::i Apps
Home
Secure
!,Qgi!!
B&gister
Login:
Dashboo,d • Cent,a .. 0 Scrublands Apothe .
User I ame :!scott anderson
Password:,..........
<) PicMonkey Scrublands Apo
public interface UserR
epository extends JpaRepository<User, Long> {
User findByUsername(String userName);
!Sign In I
}
User.java
ackage edu.cpcc.labs.secureaccess.model;
import javax.persistence. •;
@
Ent ity
public class User {
@
Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique= true)
private String username;
private String password;
public Long getid ()
return id;
public void setid(Long id ) {
this .id = id;
1c s ring ge username
return username;
public void setUsername(String username)
this .username = username;
1c String getPasswor
return password;
public void setPassword(String password)
this .password = password;
package edu.cpcc.labs.secureaccess.controlle
SecureAccessHandler.java
package edu.cpcc .labs.secureaccess.controller;
org.springframework.beans.factory.annotation .Autowired;O
}
SecureAccessHandler {
// NOTE: this is pa entication process . ..
public User findBy(String userName) {
return userRepository .findByUsername( userName ·
}
public User createuser(final String userName, final String password ) {
User newUser = new User();
newUser . setusername(userName );
newuser .setPassword(password );
return createuser( newuser);
}
/ / NOTE: this is part of the registration process •..
public User createUser(User newUser) {
· · e .re isterUser newUser);
}
[
Lesson 07 Security Login Code Execution Path
Ipackage edu.cpcc.labs.secureaccess.dao;
interface UserRepository.java
package edu.cpcc. labs. secureaccess .dao;
import org .springframework .data. jpa. repository . JpaRepository;
~epository
public interhce userRepository extends JpaRepository<User, Long> {
User find8yUsername(String userName) ;
"""'
"""'
l.Hla
"'"'"'
Login:
~::;~:::, I:.'..-- J 1
....J
package edu.cpcc.labs.secureaccess.controlle
User.java
ukage tdu.cpcc.hbs . s.curucc1n ..od1l;
iapol"t j avu.perststence.•;
~ntlty
public c hu user {
~Id
(iGeneraudValue(strntlY • Genernionfype.AUTO)
private Long ld;
@leoli.an(nulhble • ftlH, unique• true )
pdvate Str-ing uHrn-;
private Str-ina password;
public Lone getid() {
return id;
public void Htld( Long i d) {
thb , id • i d;
public void HtUHrn,..(String usern-) {
thb.unrn- • usernaat;
pu u tr n1 ge asswo
return password;
public void sttPan word(Strin1 paonword) {
thb.pnsword • pnswol"G;
SecureAccessHandler.java
l"t org. springfra11ework .beans. f actory.annotation. Autowired;O
ce;
// NOTE: this is pa entiution process ...
public User findBy(String userName) {
return userRepository .findByUsername(userName ·
public User crut eUser(fin•l String user-Na111e, fin•l String password) {
user newuser • n- user( ) ;
newuser .setUsername(userHae);
ne~ser . setPassword(password);
return createuser(newuser) ;
II NOTE: thh is part of the registration process .
public User createUser(User newuser) {
.re istel"User newUser);
UsernamePasswordAuthenticationFilter
package edu.cpcc.la s.secureaccess.controller;
SecureAcce sController.java
Vlpp1.n1 ,.,,,.,.
pul,lic Strln111tlillf1h t1rPag1() (
retul'tl ·nchter·;
ff NOTE: In Sprln1 HVC, the (IJlequ1nP,rM ilMOUllon ls UHd to rud the f - daou ilnd
fl blnd It ,utoutlcally to the p1r-ter present 1n the provldf'd ..ulOd.
If So, It 111lDf'U tlHI requtr-nt of H'ttpServleO.-que$l abjl'Ct to rud the proYid-4 data.
II tn thh CUI, both th4I u,er n- Incl pn-4 are p1ou.a in thN the 101!.n fo,,_
ll)Poslklppln1( "/ ,..1ister" )
publicStrin,:cruttt1ser((IJl1qu11tP1r•( "uHrn-• l Strln,: userfl-,
(IJl1q1,1utP1r•( "pnsword" ) Strine p1nwonl,
"Odel .ootl) (
// ched: if thh user h elre,cl)' ,..,_hte,..ci..
User fOUfldUser • hlon.:l ler .flndly(userffl..);
if (fOl.lndUUl' H null ) {
}
II In tl'tb c,.,, re,:hter the user and talc, tl'tell to the lacin P•I•
h•n<1l1r.crHttt1,er{userN- . ~uword) ;
,..,ur n "lo1ln" ;
ehe {
/Jtl'teuserh,1re,d)'rt11:htt~.•
-,dtl. ~Attributt( "11<hts", true);
retur n "r11ht1r ";
itching the user repository to this service instance ...
ired
te UserRepository user-Repository;
itching the password encoder to this urvice instance ...
owired
ate PasswordEncoder passwordEncoder;
IOTE: This method is called by the Sprina Security AuthenticationProvider
is method looks up the user usina JPA at the time of authenticat ion.
rride
pu lie UserOetails lo,1dUserByUsername{String username) {
User user " userRepos1tory . 1n ByUsername username ;
throw new UsernameNotfoundException(username);
return new ora. sprinaframework. security. core . userdetails. User(user .aetUsername() ,
user ,aetPassword( ),
1etAuthorities()) ·
// NOTE: user Details is an interf.ace.
public UserOetails reaisterUser(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 .aetPassword()));
user uvedUser ., userRepository . save(newuser );
// NOTE: the spring security user class implements a userO.tails inte
return new ora. sprinaframework. security. core. userdetails .User(saved
save
'"
au 1s .a new 1mp e ran e u _ ,
return aut hlist;

More Related Content

Similar to Lesson_07_Spring_Security_Login_NEW.pdf

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
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
How to implement multiple authentication guards in laravel 8
How to implement multiple authentication guards in laravel 8How to implement multiple authentication guards in laravel 8
How to implement multiple authentication guards in laravel 8
Katy Slemon
 
Spring Security Framework
Spring Security FrameworkSpring Security Framework
Spring Security Framework
Jayasree Perilakkalam
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
codepitbull
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Matt Raible
 
Introduction to PicketLink
Introduction to PicketLinkIntroduction to PicketLink
Introduction to PicketLink
JBUG London
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
FIDO Alliance
 
Fun With Spring Security
Fun With Spring SecurityFun With Spring Security
Fun With Spring Security
Burt Beckwith
 
Session - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptxSession - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptx
imjdabhinawpandey
 
КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022
КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022
КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022
QADay
 
You would like to verify the credentials of a user for your system..pdf
You would like to verify the credentials of a user for your system..pdfYou would like to verify the credentials of a user for your system..pdf
You would like to verify the credentials of a user for your system..pdf
sagar753267
 
10 Rules for Safer Code
10 Rules for Safer Code10 Rules for Safer Code
10 Rules for Safer Code
Quang Ngoc
 
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersJavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
FestGroup
 
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]
Olivier Dony
 
Spring Security
Spring SecuritySpring Security
Spring Security
Sumit Gole
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
Dzmitry Naskou
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
solit
 
Easy logins for JavaScript web applications
Easy logins for JavaScript web applicationsEasy logins for JavaScript web applications
Easy logins for JavaScript web applications
Francois Marier
 
securing-portlets-with-spring-security.pdf
securing-portlets-with-spring-security.pdfsecuring-portlets-with-spring-security.pdf
securing-portlets-with-spring-security.pdfjcarrey
 

Similar to Lesson_07_Spring_Security_Login_NEW.pdf (20)

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
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
 
How to implement multiple authentication guards in laravel 8
How to implement multiple authentication guards in laravel 8How to implement multiple authentication guards in laravel 8
How to implement multiple authentication guards in laravel 8
 
Spring Security Framework
Spring Security FrameworkSpring Security Framework
Spring Security Framework
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
 
Introduction to PicketLink
Introduction to PicketLinkIntroduction to PicketLink
Introduction to PicketLink
 
Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
 
Fun With Spring Security
Fun With Spring SecurityFun With Spring Security
Fun With Spring Security
 
Session - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptxSession - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptx
 
КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022
КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022
КОСТЯНТИН КЛЮЄВ «Cypress.io : Let’s go farther» Online QADay 2022
 
You would like to verify the credentials of a user for your system..pdf
You would like to verify the credentials of a user for your system..pdfYou would like to verify the credentials of a user for your system..pdf
You would like to verify the credentials of a user for your system..pdf
 
10 Rules for Safer Code
10 Rules for Safer Code10 Rules for Safer Code
10 Rules for Safer Code
 
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developersJavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
 
10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]10 Rules for Safer Code [Odoo Experience 2016]
10 Rules for Safer Code [Odoo Experience 2016]
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Spring Framework - Spring Security
Spring Framework - Spring SecuritySpring Framework - Spring Security
Spring Framework - Spring Security
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Easy logins for JavaScript web applications
Easy logins for JavaScript web applicationsEasy logins for JavaScript web applications
Easy logins for JavaScript web applications
 
securing-portlets-with-spring-security.pdf
securing-portlets-with-spring-security.pdfsecuring-portlets-with-spring-security.pdf
securing-portlets-with-spring-security.pdf
 

Recently uploaded

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 

Recently uploaded (20)

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 

Lesson_07_Spring_Security_Login_NEW.pdf

  • 1. Lesson 07 Spring Security Login Code Execution Path Lesson 07 Spring Security Project By: Scott Michael Anderson Date: 12/06/2021 V lesson-seven-spring-security [boot] [devtools] v II edu.cpcc.labs.secureaccess > J LessonSevenSpringSecurityApplication.java v II edu.cpcc.labs.secureaccess.auth > J SecureUserCredentialService.java > J WebSecurityConfigJava v II edu.cpcc.labs.secureaccess.controller > J SecureAccessControllerJava > J SecureAccessHandlerJava v II edu.cpcc.labs.secureaccess.dao > JOUserRepository.java v II edu.cpcc.labs.secureaccess.model > J UserJava •• > ~ src/main/resources •• > ~ src/test/java > ~ JRE System Library [JavaSE-1 .8] > ~ Maven Dependencies > l;, src II, target ~ HELP.md = mvnw ~ mvnw.cmd = PLEASE README !!! ID pom.xml
  • 2. FormLoginConfigurer class UsernamePasswordAuthenticationFilter Class DaoAuthenticationProvider class Lesson 07 Spring Security Application: Start-Up Code Execution Path • Java uses the filter “UsernamePasswordAuthenticationFilter” by default for the URL/login • Note: The Application Start-Up Code Execution Path does not include every class/interface/method etc.. executed during the Application Start-Up. public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { ,.. * The plaintext password used to perform Passw ordEncoder#matches (CharSequence, * String)} on when the user i s not found to avoid SEC-20S6 . •1 private static final String USER_NOT_FOUND_PASSWORD ; "userNot FoundPassword"; private PasswordEncoder passwordEncoder; ,.. * The password used to perform {@ link PasswordEncoder#matches ( CharSequence, String)} * on when the user is not found to avoid SEC- 20S6. This is necessary, because some * {@link PasswordEncoder} implementations will short circuit if the password is not * in a valid format. */ private volatile String userNotfoundEncodedPassword; private UserDetailsService userDetai lsSer vi ce; t private UserDetailsPasswordService userDetailsPasswordService; D ~ublic DaoAuthenticationProvider() { / } setPasswordEncoder( Passw ordEncoderFactories . cr eateDeLegatingPasswordEncoder( )) ; I public final class FormLoginConfigurer<H extends HttpSecurit yBuilder<H>> extends public FormLoginConfigurer( ) { l,uper (new UsernamePasswordAuthenticationFilter(), null ) ; UsernameParameter( "username" ); passwordParameter( "pas sword " ); private static final AntPathRequestM atcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestM atcher ("/ login" , "POST" ); private String usernameParameter = SPRING_SECURITY_FORM_ USERNAME_KEY; private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY; private boolean postOnly = true; ~ public UsernamePasswordAuthenticationFilter() { super (OEFAULT_ANT_PATH_REQUEST_MATCHER ) ; I :) public UsernamePasswordAuthenticationFilter(AuthenticationM anager authenticationM anager) { super(DEFAULT_ANT_PATH_REQUEST_MA TCHER , authent icationM anager ) ;
  • 3. • 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 Aut henticationProcessingFilter prior to Spring Security 3.0. Login fonns must present two parameters to this filter: a username and password. The default parameter names to use are contained in the static fields SPRING_SECURITY_FORM_USERNAME_KEY and SPRING_SECURITY_FORM_PASSWORD_KEY. The paraineter names can also be changed b setting the use rnam eParam eter and passwor dPa r am eter prope1ties. !This filter by default responds to the URL / logi n. Since:
  • 4. Lesson 07 Spring Security UsernamePasswordAuthenticationFilter • We will use the “UsernamePasswordAuthenticationFilter” to authenticate the user at URL : “http://localhost:8080/login” UsernamePasswordAuthenticationFilter UsernamePasswordAuthentication Filter - Tries to find a username/password request parameter/POST body and if found, tries to authenticate the user with those values Spring's FilterChain: Browser HTTP Request ecu, ltyContextPer lstencefllter srtfllter Logoutfllt r OetaultloglnPag G neratlngfllter OefaultlogoulPageGen ratlngfllter urlty ont xtHold rAw reR qu Anonymou Auth ntl tlonfllt r lonM nagementfllt r Exception ran latlonfllter Fllle, ecuritylnt I ceptor your @RestController/ Controller Marco Behler Notes
  • 5. Lesson 07 Security Application DaoAuthenticationProvider • “DaoAuthenticationProvider” – An AuthenticationProvider that retrieves user details from the UserDetailsService User Details Service serves as a hook to source custom credentials Filte~ uth nt c te(Authentlcat on uth) Authent·cation fals SecureUserCredenfa: tService Class DaoAuthenticationProvider Class
  • 6. Lesson 07 Spring Security Login Code Execution Path • The following slides show a high level overview of the code execution path for Lesson 07 Spring Security Code “/login” • Note: Lesson 07 Spring Security “/login” Code Execution Path does not include every class/interface/method etc.. executed during the “/login” process • We will include the Lesson 07 Spring Security Code Modules, the UsernamePasswordAuthenticationFilter, and the DaoAuthenticationProvider Lesson 07 Spring Security Project V lesson-seven-spring-security [boot] [devtools] v II edu.cpcc.labs.secureaccess > J LessonSevenSpringSecurityApplicationJava v II edu.cpcc.labs.secureaccess.auth > J SecureUserCredentialService.java > J WebSecurityConfigJava v II edu.cpcc.labs.secureaccess.controller > J SecureAccessController.java > J SecureAccessHandler.java v II edu.cpcc.labs.secureaccess.dao > J8 UserRepositoryJava v II edu.cpcc.labs.secureaccess.model > J User.java •• > ~ src/main/resources •• > ~ src/test/java > IIJ JRE System Library [JavaSE-1.8] > IIJ Maven Dependencies > ~ src ~ target ~ HELP.md mvnw l!J mvnw.cmd = PLEASE README !!! f.J pom.xml
  • 7. #1 0 Spring Security Example X + C 0 localhost:8080/login ... Apps @ Dashboard - Centra... 0 Scrublands Home Secure Logm Register Login: User ame: Password: ,--J---------"l!!I ISign In I package edu.cpcc.labs.secureaccess.controller; SecureAccessController.java package edu.cpcc.labs.secureaccess.controller; import org.springframework.beans.factory.annotation.Autowired;O @ Controller public class SecureAccessController { II Stitching the hander to the controller . @Autowired private SecureAccessHandler handl er; @GetMapping("/" ) public String getHomePage() { return "home" ; } @GetMapping("lsecure" ) public String getsecurePage() { return 11 secure11 ; } @GetMapping("llogin" ) public String getLoginPage() { return "login"; } @GetMapping("lregister" ) public String getRegisterPage() { return "register" ; } II NOTE: In Spring MVC, the @ RequestParam annotation is used to read the form data and II bind it automatically to the parameter present in the provided method. II So, it ignores the requirement of HttpServletRequest obj ect to read the provided data. II In this case, both the user name and password are passed in thru the login form @ PostMapping("lregister" ) public String createUser(@ RequestParam("username" ) String userNam e, @RequestParam("password" ) String password, Model model ) { } II check if this user is already registered . ... User foundUse r = handler .findBy( userName ); if (foundUser == null ) { } II in this case, register the user and take them to the login page .. . handler . createUser( userN ame, password ); return "login" ; else { } II the user is already registered ... System. out.println( "User is already registered . .. "); model .addAttribute( "exists" , true); return "register" ;
  • 8. UsernamePasswordAuthenticationFilter Class #2 J UsernamePasswordAuthenticationFilter.class ~ 58 59 60 61 62 •630 64 65 66 •670 68 69 70 I710 72 t 73 ;z. ., •l'- ~ 74 -~ i 75 I 76 77 "· 78 ~~: 79 m80 ij 81 I I 82 I83 . , 84 B85 •86 private String passw ordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY; private boolean postOnly = true; public UsernamePassw ordAuthenticationFilter() { super(DEFAULT_ANT_PATH_REQUEST_MATCHER ); } public UsernamePassw ordAuthenticationFilter(AuthenticationM anager authenticationManager ) { super (DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { } if (this . postOnly && !request .getMethod() .equals( "POST" )) { throw new AuthenticationServiceException( "Authentication method not supported: 11 + request .getM ethod()); J String username = obtainUsername( request ); username = (usernam e != null ) ? username : ""; username = username .trim(); String password = obtainPassw ord( request ); password = (password != null ) ? password : "" ; UsernamePassw ordAuthenticationToken authRequest = new UsernamePassw ordAuthenticationToken( username, password ); // Allow subclasses to set the "details" property setDetails( request, authRequest ); return this .getAuthenticationM anager().authenticate( authRequest );
  • 9. DaoAuthenticationProvider Class #3 J DaoAuthenticationProvider.java ~ 77 this . logger.debug( "Failed to authenticate since password does not match stored value" ); 78 throw new BadCredentialsException(this .messages 79 .getM essage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials'' )); 80 81 82 830 84 85 86 87 - ::~ 880 89 90 .. '• 91 92 93 94 95 96 97 .. 98 99 ~ 100 .101 · 102 ❖ '•103 . 104 ·: 105 ,• 106 _ §107 108 '·109 . 110 111 } } @ Override protected void doAfterPropertiesSet() { Assert . notNull(this .userDetailsService, "A UserDetailsService must be set" ); } @ Override protected final UserDetails retrieveUser(String username, UsernamePassw ordAuthenticationToken authentication) throws AuthenticationException { } prepareTimingAttackProtection(); try t } UserDetails loadedUser =this .getUserDetailsService().loadUserByUsername(username); if (loadedUser == null ) { throw new InternalAuthenticationServiceException( "UserDetailsService returned null, which is an interface contract violation" ); } return loadedUser; catch (UsernameN otFoundException ex) { mitigateAgainstTimingAttack(authentication); throw ex; } catch (InternalAuthenticationServiceException ex) { throw ex; } catch (Exception ex) { throw new InternalAuthenticationServi~eException (ex.getM essage(), ex ) ; } (t org.springframework.security.authentication.lnternalAuthenticationServiceException
  • 10. DaoAuthenticationProvider Class #4 J DaoAuthenticationProviderJava ~ 1120 verride 113 protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, 114 UserDetails user) { 115 boolean upgradeEncoding = this .userDetailsPasswordService != null 116 && this .passw ordEncoder . upgradeEncoding(user.getPassword()); 117 if (upgradeEncoding) { 118 String presentedPassword = authentication.getCredentials().toString(); 119 String newPassword = this .passwordEncoder.encode(presentedPassword); 120 user= this .userDetailsPasswordService.updatePassword(user, newPassword); 121 122 123 124 1250 126 127 128 129 130 1310 132 133 134 135 136 137 1380 139 140 141 142 143 144 1450 146 147 148 149 150 1510 152 153 154 1550 156 157 158 1 1590 160 161 } return super . createSuccessAuthentication(principal, authentication, user); } private void prepareTimingAttackProtection() { if (this .userNotFoundEncodedPassword == null ) { this .userNotFoundEncodedPassword = this .passwordEncoder.encode(USER_NOT_FOUND_PASSWORD); } } private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) { if (authentication.getCredentials() != null) { } } String presentedPassword = authentication.getCredentials().toString(); this .passwordEncoder.matches(presentedPassword, this .userNotFoundEncodedPassword); /** * Sets the PasswordEncoder instance to be used to encode and validate passw ords . If * not set, the password will be compared using * {@ link Passw ordEncoderFactor ies#createDelegatingPassw ordEncoder() } * @param passw ordEncoder m ust be an instance of one of the {@ code PasswordEncoder} * t ypes . */ public void setPasswordEncoder(PasswordEncoder passwordEncoder) { Assert.notNull(passwordEncoder, "passwordEncoder cannot be null" ); this . passwordEncoder = passwordEncoder; this .userNotFoundEncodedPassword = null; } protected PasswordEncoder getPasswordEncoder() { return this .passwordEncoder; } public void setUserDetailsService(UserDetailsService userDetailsService) { this .userDetailsService = userDetailsService; } protected UserDetailsService getUserDetailsService() { return this .userDetailsService; } 1h? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - •
  • 11. SecureUserCredentialServices Class #5 J SecureUserCredentialService.java ~ 1 package edu.cpcc.labs.secureaccess .auth; 2 30 import java. util .Arraylist;Q 16 17 // N OTE: the UserDetailsService is spring secur ity interface . 18 // N OTE: you can also use @ Component or @ Repository - in all these cases it will create a single i 190 / * 20 * N ote : N ever name your class after a technical stack 21 * the previous class name was "MySQLUserDetailsService" - we changed it to "SecureUserCredential 22 23 24 • 25 26 27 280 29 30 31 320 ; 33 34 */ @Service public class SecureUserCredentialService implements UserDetailsService { // Stitching the user repository to this service instance ... / * * Uses dependency injection to instantiate a class instance of that interface * */ @Autowired private UserRepository userRepository; 35 // Stitching the passw ord encoder to this service i nstance . . . 36 370 / * 38 * Uses dependency injecti on to instantiate a cl ass instance of that interface 39 */ 40 410 @Autowired 42 private PasswordEncoder passw ordEncoder; 43 44 45 46 470 48 49 50 51 52 53 540 55 56 57 58 59 60 61 62 63 """" // N OTE: This method is called by the Spring Securi t y AuthenticationProvider // This method looks up the user using JPA at the time of authentication. / * * "loadUserByUsername" method is used to find out if the "username" exist in * the+ * * */ @Override public UserDetails loadUserByUsername(String username ) { User user = userRepository .findByUsername( username ); } '* i~ t user == nuLL J t throw new UsernameNotFoundException( username ); } return new org . springframew ork. security .core . userdetails . User (user .getUsername() , user .getPassw ord ( ), getAuthorities ());
  • 12. #6 package edu.cpcc.labs.secureaccess.dao; interface UserRepository.java package edu.cpcc.labs.secureaccess.dao; import org.springframework.data.jpa.repository.JpaRepository; @Repository public interface UserRepository extends JpaRepository<User, Long> User findByUsername(String userName ); } {
  • 13. SecureUserCredentialServices Class #7 J SecureUserCredentialService.java ~ 1 package edu.cpcc . labs . secureaccess.auth; 2 30 import java.util.Arraylist;Q 16 17 // NOTE: the UserDetailsService is spring security interface. 18 / / NOTE: you can also use @ Component or @ Repository - in all these cases it will create a single i 190 / * 20 * Note: Never name your class after a technical stack 21 * the previous class name w as "MySQLUserDetailsService" - we changed it to "SecureUserCredential 22 */ 23 24 @ Service t 25 public class SecureUserCredentialService implements UserDetailsService { 26 27 280 29 30 31 320 , 33 34 35 36 370 38 39 40 410 42 43 44 45 46 470 48 49 50 51 52 53 540 55 56 57 58 59 60 61 62 63 C:IIA // Stitching the user repository to this service instance ... / * * Uses dependency injection to instantiate a class instance of that interface * */ @ Autowi red private UserRepository userRepository; // Stitching the password encoder to this service instance .. . / * * Uses dependency injection to instantiate a class instance of that interface */ @ Autowired private PasswordEncoder passw ordEncoder; // NOTE: This method is called by the Spring Security AuthenticationProvider // This method looks up the user using JPA at the time of authentication. / * * "loadUserByUsername" method is used to find out if the "username " exist in * the+ * * */ @Override public UserDetails loadUserByUsername(String usernam e) { User user = userRepository .findByUsername( usernam e); if (user == null ) { throw new UsernameNotFoundException( usernam e); } return new org.spr1ngTrameworK.secur1ty.core.useraeta11s.User( user .getUsername(J, user .getPassword(), getAuthorities());
  • 14. User Class #8 J UserJava ~ 1 package edu.cpcc.labs.secureaccess.model; 2 3 4 import javax.persistence. *; 5 @Entity 8 6 public class User { 7 80 9 ~ 10 11 120 ~ 13 14 ~ 15 16 f 110 18 19 20 f 210 22 23 24 .250 ~ 26 I 121 28 f 290 30 31 32 f 330 34 35 36 . 370 38 39 40 } 41 @Id @GeneratedValue (strategy = GenerationType.AUTO) private Long id ; @Column(nullable = false, unique= true ) private String username; private String password ; public Long getid() { return id; } public void setid(Long id ) { this . id = id; } public String getUsername() { return username; } public void setUsername(String username ) { this . username = username; } public String getPassword() { return password ; } public void setPassword(String password ) { this . password = password; }
  • 15. User Class #9 J User.java ~ 1 package edu.cpcc.labs.secureaccess.model; 2 3 import javax.persistence. *; 4 5 @Entity 8 6 public class User { 7 80 9 ~ 10 11 120 ~ 13 14 ~ 15 16 . 170 18 19 20 . 210 22 23 24 . 250 26 27 28 . 290 30 31 @Id @GeneratedValue (strategy = GenerationType. AUTO) private Long id ; @Column (nullable = false, unique= true ) private String username; private String passw ord; public Long getid() { return id; } public void setid(Long id ) { this .id = id; } public String getUsername() { return username; } public void setUsername(String username ) { this .username = username; } 32 - - - - - - - - - - - - - - - - - - - - - - - - l!!c~ I 35 public String getPassw ord() { return passw ord; } 36 __________________________, . 370 38 public void setPassw ord(String passw ord ) { this . passw ord = passw ord ; 39 } 40 } 41
  • 16. SecureUserCredentialServices Class #10 J SecureU serCredentialSeNicejava ~ 470 48 49 50 51 52 53 540 A 55 • 56 57 • 58 59 • 60 61 62 63 640 65 66 67 68 69 70 71 72 73 74 75 76 77 78 • 790 80 81 82 83 84 85 86 87 88 89 90 91 < 92 930 94 95 960 ,· 97 98 " 99 100 101 102 } / * * "loadUserByUsername" method is used to find out if the "username" exist in * the+ * * */ @Override public UserDetails loadUserByUsername(String username ) { User user = userRepository .findByUsername(username ); if (user == null ) { throw new UsernameNotFoundException( username ); } return new org.springframework.security.core.userdetails.User( user .getUsername(), user .getPassword(), getAuthorities()); } I* * registerUser is taking an instance of the "User" and taking the password from * that user then registerUser is encoding that password (Hashed ) . Passw ord is * encoded/ encrypted and then saved into the database * * Once that is complete, he calls the UserRepository (the handle to the * repository ) and calls save passing in the instance of the User . * * Then he gives back the UserDetails (an object in Spring) * * * *I // NOTE : User Details is an interface. public UserDetails registerUser(User newUser ) { } // NOTE: an instance of passw ord encoder is used to encrypt the passw ord when it is stored in the database . .. newUser .setPassword( passw ordEncoder .encode( newUser .getPassword())); User savedUser = userRepository .save( newUser ); // NOTE: the spring security User class implements a UserDetails interface... return new org.springframew ork .security.core . userdetails .User( savedU ser. getUsername( ), savedUser .getPassword(), getAuthorities()); // NOTE: Typically this method should query a database and return the ACL - access level list. / * * getAuthorities - provides access levels for users "What can I do" * , private List<SimpleGrantedAuthority> getAuthorities() { List<SimpleGrantedAuthority> authlist = new Arraylist<>(); authlist .add (new SimpleGrantedAuthority( "ROLE_USER")); return authlist; }
  • 17. SecureUserCredentialServices Class #11 J SecureUserCredentialServiceJava ~ 320 @Autowired ~ 33 private UserRepository userRepository; 34 35 36 370 38 39 40 410 '° 42 ✓ 43 48 49 50 51 52 53 540 55 56 57 58 59 60 61 62 63 // Stitching the password encoder to this service instance ... / * * Uses dependency injection to instantiate a class instance of that interface */ @Autowired private PasswordEncoder passwordEncoder; // NOTE: This method is called by the Spring Security AuthenticationProvider // This method looks up the user using JPA at the time of authentication. / * * "loadUserByUsername" method is used to find out if the "username" exist in * the+ * * */ @Override public UserDetails loadUserByUsername(String username ) { User user = userRepository .findByUsername( username ); if (user == null ) { throw new UsernameNotFoundException( username ); } return new org.springframew ork.security.core.userdetails.User( user .getUsername(), user .getPassword(), getAuthorities()); }
  • 18. DaoAuthenticationProvider Class #12 J DaoAuthenticationProviderJava ~ 32 " < 330 /** 34 * An {@ link AuthenticationProvider} implementation that retrieves user details from a * {@ link UserDetailsService} . 35 36 37 38 39 40 41 420 43 44 45 46 47 48 49 500 51 52 53 54 55 56 57 58 59 60 61 620 63 64 65 660 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 * * @author Ben Alex * @author Rob Winch */ public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { /** * 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 = "userN otFoundPassword" ; private PasswordEncoder passwordEncoder; /** * The password used to perform {@l ink 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 f ormat. */ private volatile String userNotFoundEncodedPassword; private UserDetailsService userDetailsService; private UserDetailsPasswordService userDetailsPasswordService; public DaoAuthenticationProvider() { setPasswordEncoder(Passw ordEncoderFactories.createDelegatingPasswordEncoder( ) ); } ~ verride @ SuppressWarnings( "deprecation" ) protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { this .logger .debug( "Failed to authenticate since no credentials provided" ); throw new BadCredentialsException(this .messages .getM essage( "AbstractUserDetailsAuthenticationProvider . badCredentials", "Bad credentials")); } String presentedPassword = authentication .getCredentials().toString(); if ( !this .passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { this .logger.debug( "Failed to authenticate since password does not match stored value" ); } throw new BadCredentialsException(this .messages .getM essage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials" ));
  • 19. DaoAuthenticationProvider Class #13 J DaoAuthenticationProviderJava ~ 97 } 98 99 100 101 102 103 104 105 106 107 108 109 110 111 ij1120 -113 ::114 ·= 11s :116 ~117 .. 1 118 -~119 .h20 ,. . ,1121 i122 :; (§(123 124 } return loadedUser; } catch (UsernameN otFoundException ex) { mitigateAgainstTimingAttack(authentication); throw ex; } catch (InternalAuthenticationServiceException ex) { throw ex; } catch (Exception ex) { throw new InternalAuthenticationServiceException(ex.getM essage(), ex); } verride protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) { } boolean upgradeEncoding = this .userDetailsPassw ordService != null && this .passw ordEncoder.upgradeEncoding(user.getPassword()); if (upgradeEncoding) { } String presentedPassword = authentication.getCredentials().toString(); String newPassw ord = this .passw ordEncoder.encode(presentedPassword); user= this .userDetailsPasswordService.updatePassw ord(user, newPassw ord); return super .createSuccessAuthentication(principal, authentication, user);
  • 20. SecureAccessController Class #14 J SecureAccessControllerJava ~ 1 package edu.cpcc.labs.secureaccess.controller; 2 30 import org.springframework.beans.factory.annotation.Autowired;Q 11 12 8 13 14 15 160 '° 17 ✓ 18 19 1200 ' . ,•· ···21 ;, •·22 123 : ·24 25 260 f 27 28 29 30 310 f 32 33 34 35 360 f 37 38 39 40 @Controller public class SecureAccessController { I // Stitching the hander to the controller. @Autowired private SecureAccessHandler handler; @GetMapping ("/" ) public String getHomePage() { return "home" ; } @GetMapping("/secure" ) public String getSecurePage() { return "secure" ; } @GetMapping ("/login" ) public String getloginPage() { return "login" ; } @GetMapping ("/register" ) public String getRegisterPage() { return "register" ; }
  • 21. 1e txecut1on Patn UsernamePasswordAuthenticationFilter package edu.cpcc.la s.secureaccess.controller; SecureAcce sController.java package edu. cpcc. labs. secureaccess. co roller; import org .springframework. beans . f ac ry.annotation. Autowired;O ~ontroller public class SecureAccessController // Stitching t he hander t o the ntroller. {IAut owired private secureAccessHandler h ler; @GetMapping( "/" ) public String get HomePage() return "home"; @GetMapping( "/secure" ) public String getSecurePag return "secure"; @GetMapping( "/login" ) public String getLoginPage () return "login" ; // NOTE : In Spring MVC, the @ RequestParam annotation is used to read the form dat a and / / bind it automatically to the parameter present in the provided method . /I So, it ignores the requirement of HttpServletRequest object to read the provided data. // In this case, both the user name and password are passed in thru the login form ~Post Mapping( ··/register.. ) public Stri ng createUser(, R equestParam( "username" ) String userName, f Request Param( "password") String password, Model model) { // check if this user is already regist ered . ... user foundUser • handler .findBy(userName) j if (founduser •• null) { } // in this case, register the user and take them to the login page . . . handler . createUser(userName, password) ; return "l ogin" ; else { / / the user is already registered .. . model. addAtt ribute("edsts" , true ); return "register"; } DaoAuthenticationProvider ge edu.cpcc.labs.s th; • rv1ce Special service class that imple ents the UserDetailsService Added to configuration so each quest can be validated and authenticated. ilsService is spring security interface. lso use @Component or @ Repository - in all these cases ea single instance of this class . SecureUserCredentialService implements UserDetailsService { itching the user repository to this service instance ... wired te UserRepository userRepository; titching the passw ord encoder to this service instance .. . owired rride passwordEncoder; is called by the Spring Security AuthenticationProvider up the user using JPA at the time of authentication. lie UserDetails loadUserByUsername(String username) { org.springframew ork. security .core.userdetails .User(user .getUsername () , user .getPassw ord () , getAuthorities ())· // N OTE : User Details is an interface . public UserDetails registerUser(User new User) { // N OTE : an instance of passw ord encoder is used to encrypt the // password when it is stored in the database . . . newUser .setPassw ord (passwordEncoder .encode(new User .getPassword ())) ; User savedUser = userRepository .save(new User ); • // N OTE: the spring security User class implements a UserOetails inte return new org .springframew ork.security.core.userdetails.User(saved ace .. . r .getUsername () . er.getPassw ord () , horities ()) ; save get // NOTE: Typically this method should query a database // the ACL - access level list. private 1st< imp e rante ut ority> get ut orities List<SimpleGrantedAuthority> authlist = new Arraylist<>() ; authlist .add (new SimpleGrantedAuthority("ROLE_USER")) ; return authlist; }
  • 22. package edu.cpcc.labs.secureaccess.dao; interface UserRepository.java package edu.cpcc.labs.secureaccess.dao; import org.springframework.data.jpa . repository.JpaRepository; @ Repository Spring Security Example X + ~ X 0 localhosl8080/login ::i Apps Home Secure !,Qgi!! B&gister Login: Dashboo,d • Cent,a .. 0 Scrublands Apothe . User I ame :!scott anderson Password:,.......... <) PicMonkey Scrublands Apo public interface UserR epository extends JpaRepository<User, Long> { User findByUsername(String userName); !Sign In I } User.java ackage edu.cpcc.labs.secureaccess.model; import javax.persistence. •; @ Ent ity public class User { @ Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(nullable = false, unique= true) private String username; private String password; public Long getid () return id; public void setid(Long id ) { this .id = id; 1c s ring ge username return username; public void setUsername(String username) this .username = username; 1c String getPasswor return password; public void setPassword(String password) this .password = password; package edu.cpcc.labs.secureaccess.controlle SecureAccessHandler.java package edu.cpcc .labs.secureaccess.controller; org.springframework.beans.factory.annotation .Autowired;O } SecureAccessHandler { // NOTE: this is pa entication process . .. public User findBy(String userName) { return userRepository .findByUsername( userName · } public User createuser(final String userName, final String password ) { User newUser = new User(); newUser . setusername(userName ); newuser .setPassword(password ); return createuser( newuser); } / / NOTE: this is part of the registration process •.. public User createUser(User newUser) { · · e .re isterUser newUser); } [
  • 23. Lesson 07 Security Login Code Execution Path Ipackage edu.cpcc.labs.secureaccess.dao; interface UserRepository.java package edu.cpcc. labs. secureaccess .dao; import org .springframework .data. jpa. repository . JpaRepository; ~epository public interhce userRepository extends JpaRepository<User, Long> { User find8yUsername(String userName) ; """' """' l.Hla "'"'"' Login: ~::;~:::, I:.'..-- J 1 ....J package edu.cpcc.labs.secureaccess.controlle User.java ukage tdu.cpcc.hbs . s.curucc1n ..od1l; iapol"t j avu.perststence.•; ~ntlty public c hu user { ~Id (iGeneraudValue(strntlY • Genernionfype.AUTO) private Long ld; @leoli.an(nulhble • ftlH, unique• true ) pdvate Str-ing uHrn-; private Str-ina password; public Lone getid() { return id; public void Htld( Long i d) { thb , id • i d; public void HtUHrn,..(String usern-) { thb.unrn- • usernaat; pu u tr n1 ge asswo return password; public void sttPan word(Strin1 paonword) { thb.pnsword • pnswol"G; SecureAccessHandler.java l"t org. springfra11ework .beans. f actory.annotation. Autowired;O ce; // NOTE: this is pa entiution process ... public User findBy(String userName) { return userRepository .findByUsername(userName · public User crut eUser(fin•l String user-Na111e, fin•l String password) { user newuser • n- user( ) ; newuser .setUsername(userHae); ne~ser . setPassword(password); return createuser(newuser) ; II NOTE: thh is part of the registration process . public User createUser(User newuser) { .re istel"User newUser); UsernamePasswordAuthenticationFilter package edu.cpcc.la s.secureaccess.controller; SecureAcce sController.java Vlpp1.n1 ,.,,,.,. pul,lic Strln111tlillf1h t1rPag1() ( retul'tl ·nchter·; ff NOTE: In Sprln1 HVC, the (IJlequ1nP,rM ilMOUllon ls UHd to rud the f - daou ilnd fl blnd It ,utoutlcally to the p1r-ter present 1n the provldf'd ..ulOd. If So, It 111lDf'U tlHI requtr-nt of H'ttpServleO.-que$l abjl'Ct to rud the proYid-4 data. II tn thh CUI, both th4I u,er n- Incl pn-4 are p1ou.a in thN the 101!.n fo,,_ ll)Poslklppln1( "/ ,..1ister" ) publicStrin,:cruttt1ser((IJl1qu11tP1r•( "uHrn-• l Strln,: userfl-, (IJl1q1,1utP1r•( "pnsword" ) Strine p1nwonl, "Odel .ootl) ( // ched: if thh user h elre,cl)' ,..,_hte,..ci.. User fOUfldUser • hlon.:l ler .flndly(userffl..); if (fOl.lndUUl' H null ) { } II In tl'tb c,.,, re,:hter the user and talc, tl'tell to the lacin P•I• h•n<1l1r.crHttt1,er{userN- . ~uword) ; ,..,ur n "lo1ln" ; ehe { /Jtl'teuserh,1re,d)'rt11:htt~.• -,dtl. ~Attributt( "11<hts", true); retur n "r11ht1r "; itching the user repository to this service instance ... ired te UserRepository user-Repository; itching the password encoder to this urvice instance ... owired ate PasswordEncoder passwordEncoder; IOTE: This method is called by the Sprina Security AuthenticationProvider is method looks up the user usina JPA at the time of authenticat ion. rride pu lie UserOetails lo,1dUserByUsername{String username) { User user " userRepos1tory . 1n ByUsername username ; throw new UsernameNotfoundException(username); return new ora. sprinaframework. security. core . userdetails. User(user .aetUsername() , user ,aetPassword( ), 1etAuthorities()) · // NOTE: user Details is an interf.ace. public UserOetails reaisterUser(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 .aetPassword())); user uvedUser ., userRepository . save(newuser ); // NOTE: the spring security user class implements a userO.tails inte return new ora. sprinaframework. security. core. userdetails .User(saved save '" au 1s .a new 1mp e ran e u _ , return aut hlist;