Java EE Application Security With PicketLinkpigorcraveiro
In this presentation we will take a look at PicketLink, a security framework for Java EE and learn how its identity management, authentication and authorization features can be used to address the security requirements for all aspects of application development.
Java EE 8 security and JSON binding APIAlex Theedom
Java EE Security and JSON Binding are two new APIs in the Java EE 8 release. The security API provides consistencies between containers with a simple annotation-driven model while JSON Binding completes Java EEs JSON APIs and is a real alternative to Jackson and Gson. In this presentation, I will walk through coding examples from both APIs and by the end of the presentation, you will understand how these two new APIs add to the advancement of the Java EE platform.
Step-by-step Development of an Application for the Java Card Connected PlatformEric Vétillard
A JavaOne presentation that describes the Java Card Connected development model, based on a practical example.
Beyond Java Card Connected, could be interesting for people who want to develop small embedded Web servers.
Java EE Application Security With PicketLinkpigorcraveiro
In this presentation we will take a look at PicketLink, a security framework for Java EE and learn how its identity management, authentication and authorization features can be used to address the security requirements for all aspects of application development.
Java EE 8 security and JSON binding APIAlex Theedom
Java EE Security and JSON Binding are two new APIs in the Java EE 8 release. The security API provides consistencies between containers with a simple annotation-driven model while JSON Binding completes Java EEs JSON APIs and is a real alternative to Jackson and Gson. In this presentation, I will walk through coding examples from both APIs and by the end of the presentation, you will understand how these two new APIs add to the advancement of the Java EE platform.
Step-by-step Development of an Application for the Java Card Connected PlatformEric Vétillard
A JavaOne presentation that describes the Java Card Connected development model, based on a practical example.
Beyond Java Card Connected, could be interesting for people who want to develop small embedded Web servers.
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Matt Raible
During this presentation, you'll learn how to implement authentication in your Java web applications using Java EE 7 Security, Spring Security and Apache Shiro. This session will also touch on best practices for securing a REST API and using SSL.
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Matt Raible
This presentation shows you how to implement authentication in your Java web applications using Java EE 7 Security, Spring Security and Apache Shiro. It also touches on best practices for securing a REST API and using SSL.
Presentation by Peter Skopek (JBoss by Red Hat) delivered at the London JBoss User Group event on the 30th of April 2014.
Presentation
Introductory talk to PicketLink from Federation through to Identity Management.
What is PicketLink?
PicketLink is an umbrella project for security and identity management for Java Applications. PicketLink is an important project under the security offerings from JBoss.
A Picket Fence is a secure system of pickets joined together via some type of links. Basically, the Pickets by themselves do not offer any security. But when they are brought together by linking them, they provide the necessary security.
This project is that link for other security systems or systems to bring together or join, to finally provide the necessary secure system.
For more information visit http://picketlink.org/
A tutorial on how the process of writing an application using a browser’s WebAuthn API, plus how to install a server, how to generate authentication challenges & responses, and how to integrate with related IAM infrastructure.
Code: https://github.com/fido-alliance/webauthn-demo
Live slides: http://slides.com/herrjemand/jan-2018-fido-seminar-webauthn-tutorial#/
You would like to verify the credentials of a user for your system..pdfsagar753267
You would like to verify the credentials of a user for your system.
Listed next is a class names Security, which authenticates a user and password.
(Note that this example is really not secure. Typically, passwords would be
encrypted or stored in a database.)
class Security
{
public:
static int validate(string username, string password);
};
int Security::validate(string username, string password)
{
if ((username == "abbott") && (password == "monday"))return 1;
if ((username == "costello") && (password == "tuesday"))return 2;
return 0;
}
Break this class into two files, a file with the header Security.h and a file with the
implementation
Security.cpp
Next, create two more classes that use Security class by including the header file. The first class
should
be named Administrator and contain a function named Login that returns true if a given
username and
password have administrator clearance. The second class should be named User and contain a
function
named Login that returns true if a given username and password have either user or
administrator
clearance
Both the User and Administrator classes should be split into separate files for the header and
implementation.
Finally, write a main function that invokes the login function for both the User and
Administrator classes
to test if they work property. The main function should be in a separate file. Be sure to use
#ifndef
directive to ensure that no header file is included more than once.
Here is what i have so far:
security:
#ifndef SECURITY_H_
#define SECURITY_H_
#include
using namespace std;
class Security {
public:
static int validate(string username, string password);
};
#endif /* SECURITY_H_ */
administrator:
#ifndef SECURITY_H_
#define SECURITY_H_
#include
using namespace std;
class Security {
public:
static int validate(string username, string password);
};
#endif /* SECURITY_H_ */
user:
#ifndef USER_H_
#define USER_H_
#include
using namespace std;
class User {
public:
static bool Login(string username, string password);
};
#endif /* USER_H_ */
security.cpp:
#include "Security.h"
int Security::validate(string username, string password) {
if (username == "abbott" && password == "monday") return 1;
if (username == "abbott" && password == "monday") return 2;
system("pause")
; return 0;
}
user.cpp:
#include "User.h"
bool User::Login(string username, string password) {
return username == "user" && password == "user";
}
administrator.cpp:
#include "Administrator.h"
bool Administrator::Login(string username, string password) {
return username == "admin" && password == "admin";
}
main.cpp:
#include
#include "Security.h"
#include "User.h"
#include "Administrator.h"
int main() {
system("pause")
; return 0;
}
i cannot test it. i think there needs to be something in my main.cpp file but it will not run the
program as instructed in the above instructiojns.
JavaFest. Nanne Baars. Web application security for developersFestGroup
Security is an important topic for developers however security is often an afterthought in a project. This presentation will focus on practices which developers need to be aware of, and make security fun again. This is an in depth talk about 10 topics not an overview for security best practices.
10 Rules for Safer Code [Odoo Experience 2016]Olivier Dony
In this talk, we will cover the top 10 development mistakes that lead to security issues. Olivier Dony will go through all the security issues we have had over the past 3 years and give tips on how to avoid the traps for safer Odoo code.
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
Виктор Короневич, Минск. Senior Software Test Automation Engineer with 3+ years of experience specializing in automation on Java, http://www.linkedin.com/in/agileseph
«Автоматизация тестирования сложных систем: mixed mode automated test case.» Использование Selenium + jUnit + Frank + custom java tools для тестирования Web + DB + Web Services + iOS. Development секция.
Handling user passwords safely is hard, but replacing passwords on the web in a reasonable way is even harder. Really, this should have been in the browser all along. In this talk you we will see how Persona attempts to solve this issue.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
More Related Content
Similar to Lesson_07_Spring_Security_Login_NEW.pdf
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Matt Raible
During this presentation, you'll learn how to implement authentication in your Java web applications using Java EE 7 Security, Spring Security and Apache Shiro. This session will also touch on best practices for securing a REST API and using SSL.
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...Matt Raible
This presentation shows you how to implement authentication in your Java web applications using Java EE 7 Security, Spring Security and Apache Shiro. It also touches on best practices for securing a REST API and using SSL.
Presentation by Peter Skopek (JBoss by Red Hat) delivered at the London JBoss User Group event on the 30th of April 2014.
Presentation
Introductory talk to PicketLink from Federation through to Identity Management.
What is PicketLink?
PicketLink is an umbrella project for security and identity management for Java Applications. PicketLink is an important project under the security offerings from JBoss.
A Picket Fence is a secure system of pickets joined together via some type of links. Basically, the Pickets by themselves do not offer any security. But when they are brought together by linking them, they provide the necessary security.
This project is that link for other security systems or systems to bring together or join, to finally provide the necessary secure system.
For more information visit http://picketlink.org/
A tutorial on how the process of writing an application using a browser’s WebAuthn API, plus how to install a server, how to generate authentication challenges & responses, and how to integrate with related IAM infrastructure.
Code: https://github.com/fido-alliance/webauthn-demo
Live slides: http://slides.com/herrjemand/jan-2018-fido-seminar-webauthn-tutorial#/
You would like to verify the credentials of a user for your system..pdfsagar753267
You would like to verify the credentials of a user for your system.
Listed next is a class names Security, which authenticates a user and password.
(Note that this example is really not secure. Typically, passwords would be
encrypted or stored in a database.)
class Security
{
public:
static int validate(string username, string password);
};
int Security::validate(string username, string password)
{
if ((username == "abbott") && (password == "monday"))return 1;
if ((username == "costello") && (password == "tuesday"))return 2;
return 0;
}
Break this class into two files, a file with the header Security.h and a file with the
implementation
Security.cpp
Next, create two more classes that use Security class by including the header file. The first class
should
be named Administrator and contain a function named Login that returns true if a given
username and
password have administrator clearance. The second class should be named User and contain a
function
named Login that returns true if a given username and password have either user or
administrator
clearance
Both the User and Administrator classes should be split into separate files for the header and
implementation.
Finally, write a main function that invokes the login function for both the User and
Administrator classes
to test if they work property. The main function should be in a separate file. Be sure to use
#ifndef
directive to ensure that no header file is included more than once.
Here is what i have so far:
security:
#ifndef SECURITY_H_
#define SECURITY_H_
#include
using namespace std;
class Security {
public:
static int validate(string username, string password);
};
#endif /* SECURITY_H_ */
administrator:
#ifndef SECURITY_H_
#define SECURITY_H_
#include
using namespace std;
class Security {
public:
static int validate(string username, string password);
};
#endif /* SECURITY_H_ */
user:
#ifndef USER_H_
#define USER_H_
#include
using namespace std;
class User {
public:
static bool Login(string username, string password);
};
#endif /* USER_H_ */
security.cpp:
#include "Security.h"
int Security::validate(string username, string password) {
if (username == "abbott" && password == "monday") return 1;
if (username == "abbott" && password == "monday") return 2;
system("pause")
; return 0;
}
user.cpp:
#include "User.h"
bool User::Login(string username, string password) {
return username == "user" && password == "user";
}
administrator.cpp:
#include "Administrator.h"
bool Administrator::Login(string username, string password) {
return username == "admin" && password == "admin";
}
main.cpp:
#include
#include "Security.h"
#include "User.h"
#include "Administrator.h"
int main() {
system("pause")
; return 0;
}
i cannot test it. i think there needs to be something in my main.cpp file but it will not run the
program as instructed in the above instructiojns.
JavaFest. Nanne Baars. Web application security for developersFestGroup
Security is an important topic for developers however security is often an afterthought in a project. This presentation will focus on practices which developers need to be aware of, and make security fun again. This is an in depth talk about 10 topics not an overview for security best practices.
10 Rules for Safer Code [Odoo Experience 2016]Olivier Dony
In this talk, we will cover the top 10 development mistakes that lead to security issues. Olivier Dony will go through all the security issues we have had over the past 3 years and give tips on how to avoid the traps for safer Odoo code.
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
Виктор Короневич, Минск. Senior Software Test Automation Engineer with 3+ years of experience specializing in automation on Java, http://www.linkedin.com/in/agileseph
«Автоматизация тестирования сложных систем: mixed mode automated test case.» Использование Selenium + jUnit + Frank + custom java tools для тестирования Web + DB + Web Services + iOS. Development секция.
Handling user passwords safely is hard, but replacing passwords on the web in a reasonable way is even harder. Really, this should have been in the browser all along. In this talk you we will see how Persona attempts to solve this issue.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Transform Your Communication with Cloud-Based IVR SolutionsTheSMSPoint
Discover the power of Cloud-Based IVR Solutions to streamline communication processes. Embrace scalability and cost-efficiency while enhancing customer experiences with features like automated call routing and voice recognition. Accessible from anywhere, these solutions integrate seamlessly with existing systems, providing real-time analytics for continuous improvement. Revolutionize your communication strategy today with Cloud-Based IVR Solutions. Learn more at: https://thesmspoint.com/channel/cloud-telephony
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppGoogle
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-fusion-buddy-review
AI Fusion Buddy Review: Key Features
✅Create Stunning AI App Suite Fully Powered By Google's Latest AI technology, Gemini
✅Use Gemini to Build high-converting Converting Sales Video Scripts, ad copies, Trending Articles, blogs, etc.100% unique!
✅Create Ultra-HD graphics with a single keyword or phrase that commands 10x eyeballs!
✅Fully automated AI articles bulk generation!
✅Auto-post or schedule stunning AI content across all your accounts at once—WordPress, Facebook, LinkedIn, Blogger, and more.
✅With one keyword or URL, generate complete websites, landing pages, and more…
✅Automatically create & sell AI content, graphics, websites, landing pages, & all that gets you paid non-stop 24*7.
✅Pre-built High-Converting 100+ website Templates and 2000+ graphic templates logos, banners, and thumbnail images in Trending Niches.
✅Say goodbye to wasting time logging into multiple Chat GPT & AI Apps once & for all!
✅Save over $5000 per year and kick out dependency on third parties completely!
✅Brand New App: Not available anywhere else!
✅ Beginner-friendly!
✅ZERO upfront cost or any extra expenses
✅Risk-Free: 30-Day Money-Back Guarantee!
✅Commercial License included!
See My Other Reviews Article:
(1) AI Genie Review: https://sumonreview.com/ai-genie-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
#AIFusionBuddyReview,
#AIFusionBuddyFeatures,
#AIFusionBuddyPricing,
#AIFusionBuddyProsandCons,
#AIFusionBuddyTutorial,
#AIFusionBuddyUserExperience
#AIFusionBuddyforBeginners,
#AIFusionBuddyBenefits,
#AIFusionBuddyComparison,
#AIFusionBuddyInstallation,
#AIFusionBuddyRefundPolicy,
#AIFusionBuddyDemo,
#AIFusionBuddyMaintenanceFees,
#AIFusionBuddyNewbieFriendly,
#WhatIsAIFusionBuddy?,
#HowDoesAIFusionBuddyWorks
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
E-commerce Application Development Company.pdfHornet Dynamics
Your business can reach new heights with our assistance as we design solutions that are specifically appropriate for your goals and vision. Our eCommerce application solutions can digitally coordinate all retail operations processes to meet the demands of the marketplace while maintaining business continuity.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
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 ());
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" ));
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;