You are on page 1of 106
Zero To Master Spring Security along with JWT, OAUTH2 SECURITY [How can Timplement security tomy ‘weh/mobile applications 0 that there wont be any security breaches in my application? PASSWORDS MULTIPLE LOGINS. "How cau Timplereat a mechanism suhete the user will login only use tel SPRING SECURITY Most Common Questions? eaz) bytes FINE GRAINED SECURITY ane ‘ach ee of my appleation ‘sing authorization rues? me CSRF & CORS What i CSRF attacks and CCORS restietins. How to od JWT & OAUTH? ‘What is WT and OAUTH, How Lean protect my web pplication sing them? PREVENTING ATTACKS How to prevent securty attacks ike Brate force, stealing of data, session Bi ‘Welcome to the ‘world of Spring Security COURSE AGENDA Securing a web app Important Interfaces, using Spring Classes, Annotations Security of Spring Security 4 Configuring Authentication & Authorization for a web app Implementing role based access using ROLES, AUTHORITIES COURSE AGENDA Different strategies that Spring security pean aas is security using coming to passwords cml 4 How to handle most common attacks like CORS, CSRF with Spring Security COURSE AGENDA Deep dive on Deep dive on JWT =e peed Gite zole in (OAUTH, OpenID & Authorization Authentication & securing aweb servers available a application using the like Keycloak same ae Important topics of Security like Hashing, Tokens & many more SPRING SECURITY eo PROJECT ROADMAP tes MILESTONE 5 Ma Finally he application will, Method level security wil OAUTH2/0pen wrth custom ters in the MILESTONE 5 MILESTONE 2 aaa a INTRODUCTION TO SECURITY byte es WHAT & WHY Have you ever observed how well Banks are protected? Why Banks are well secured ? Because they hold valuable assets inside it vata eaz) ?CURITY bytes WHAT & WHY a Don't you think all hackers will steal the valuable data, Then why not secure a if web app is not them? properly secured ? eaz) INTRODUCTION TO SECURITY WHAT & WHY WHAT IS SECURITY? Security is for protecting your data and business Iogie inside your web applications SECURITY IS AN NON FUN REQ Security is very important similar to scalability, performance and availabilty No client will specifically asks that I need security SECURITY FROM DEV PHASE Security should be considered right from eet eae eee eens bytes DIFFERENT TYPES OF SECURITY Security fora web application wil be implemented in different way ike using firewalls HTTPS, SSL. Authentication, Authorization ete WHY SECURITY IMPORTANT? Security doesn’t mean only loosing data or money but also the brand and trust fom your uiera which you Inne built over years AVOIDING MOST COMMON ATTACKS: ‘Using Security we should also avoid most common security attacks lke CSRF, Broken Authentication inside our application, ‘WHY SPRING SECURITY ? eaz} bytes y Application security is not fim and challenging to implement with our custom code/framework. Spring Security built by a team at Spring who are good at security by considering all the security scenarios, Using Spring Security, we can secure web apps with minimum configurations, So there is no need ta re-invent the wheel here, sg, Sing Socurity hans the common seit vlnersiites ie CSRF, COR te. Forany scary 8 ame ee ee er ee ee roe ee eee eters Using Spring Security we ean secure our pages/API paths, enforce roles, method level security ete, With minimum configurations easily Spring Seourity supports various standards of security to implement authentication, like using: tusername/password authentication, JWT tokens, OAuth2, OpenID ete SERVLETS & FILTERS byte Ss he Urrien! Seenerie insider ct eerient 1 Seon seb apps, Servlet Container (Web Server) takes care of trusating hic HTTP mestegesfor Jat fale Seer aaei DE a ne of the movil ase serstet container ie Apache ‘Tomeal, Servlet Container converts the HTTP mestages ito a eingeets Seroetequest and hand over to Servet method asa parameter =] =] Sinry Serkctpona ttn as aut fo Set Container from Servlet. So everything we write tnstde Java teeb appa are driven by Servlets We Role of Filters Filters inside Sova seb opblications can be need to intercept Soe tach requet/ response and do ome pre work before our Iusines logic. So using the same flter, Spring Security tnforeesecrity Baved an our configurations inside sorb ‘pplication ag: User entered credentials SPRING SECURITY INTERNAL FLOW Authentication eaz) bytes Spring Security Filters Authentication Manager Authentication Providers Security Context UserDecails| Manager Service Password Encoder SPRING SECURITY INTERNAL FLOW byte S he Spring Security Filters A series of Spring Security filters inteeep cach rue 2 ror tgether ta identify if Authentication is rquied or ot. I anthentcaion i required ccordingly nage the nr ta login page or nae the exiting dette word daring initial antheteaton Authentication Filters lke UsernamePasrwordduthenticationF iter will extract nsername/pasncord from HTTP request & prepare duthentcetion type object Becaure Authentication i the core stondard of Horing authenticated user detail nadie Spring Security framework AuthenticationManager Once recived request fom fille delgoes the validating of the wer delist the nthenticaton providers avilable Since ther a be Inatple providers ase am pp tthe reams of the uhentiatonNanage to manage al the authentication provider vata AuthenticationProvider “AuthentictionProviders has al the core lgie of validating wer details for authentication UserDetailsManager/UserDetailsSer UserDetailsManager/UserDetailsService help in retrieving, eatin, updating, deleting the User Detail from the DB/torage syatems PasswordEncoder Service interface that help in encoding & hashing pasnvords. Otherwite swe may have to live with lain text patrwords @ SccurityContext Once the veguert has been authenticated, the Authentication vill ually be stared n a thread-local SeewityContest managed by the SecnrityContestHolder This helps during the upeomsng requests from the some er SEQUENCE FLOW bytes SPRING SECURITY DEFAULT BEHAVIOUR {DtinieinbenProvier [:rsemarCtavione Sag Sey Fe Soo 2) ar ing at se age etd nd tr Det inPgetrerinier era ae: ieee Uae ede nd {ye en ein ewig py SEQUENCE FLOW eaz! SECURITY DEFAULT BEHAVIOUR bytes © x00: ver rte a ‘UseraineParewordAuthenticationToken authenticated) @ © srenenton <> Authentication Flcers Provider Manager Detaalely aman nica @ || Qa SS Se -<> hentieationProvider dondUertiyremamed @ |] @ vseera1s < requests.anyRequest().authenticated()); http.formLogin(withDefaults()); http.httpBasic(withDefaults{)); Ama msv ar al 116 (OH CUSTOM SECURITY CONFIGURATIONS eazy INSIDE SPRING SECURITY FRAMEWORK ytés We can secure the web application APIs, Paths as per our custom requirements using Spring Security framework like shown below, fel oad aa h(t oa @ SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { TE eer am Ca Gt eae ay Geese ).authenticated() Rea ire ; )permitAllO) er torr mea TO) httpBasic(Customizer.withDefaults()): Dor ae DENY ALL SECURITY CONFIGURATIONS eazy INSIDE SPRING SECURITY FRAMEWORK ytés We can deny all the requests coming towards our web application APIs, Paths using Spring Security Jramework like shown below, iM Rite ear arc i hE SecurityFilterChain default SecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((requests) -> requests.anyRequest().denyAll()) formLogin(Customizer.withDefaults()) -httpBasic(Customizer.withDefaults()):; return http.build(); PERMIT ALL SECURITY CONFIGURATIONS eazy INSIDE SPRING SECURITY FRAMEWORK ytés We can permit all the requests coming towards our web application APIs, Paths using Spring Security Jramework like shown below, Meeker acre EG SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests((requests) -> requests.anyRequest().permitAll()) .formLogin(Customizer.withDefaults()) httpBasic(Customizer.withDefaults()); return http.build(); CONFIGURE USERS bytes USING /InMemoryUserDetailsManager lytés Instead of defining a single user inside application.properties, as a next step we can define multiple users along with their authorities with the help of InMemoryUserDetatlsManager & UserDetatls CCR ares ear ey Ves e TRON a orae teste e ate a8) Oecd ) eer nel ) emg ) build() Orso RON ie ee ee ge telaro a Approach 1 where we use withDefaultPasswordEncoder() method while creating the user details Pete) password( ) Raa Erie(OH InMemoryUserDetailsManager(admin, user): CONFIGURE USERS eazy USING /InMemoryUserDetailsManager bytes Instead of defining a single user inside application.properties, as a next step we can define multiple users along with their authorities with the help of InMemoryUserDetailsManager & UserDetails erent prsne(O Cee eee tera Ie Uae Pee return new InMemoryUseretailsManager(admin, user); Approach 2 where we create a bean of PasswordEncoder separately public PasswordEncoder passwordEnc return NoOpPasswordEncoder getInstance(): , ag: User entered credentials SPRING SECURITY INTERNAL FLOW Authentication eaz) bytes Spring Security Filters Authentication Manager Authentication Providers Security Context UserDecails| Manager Service Password Encoder USER MANAGEMENT IMPORTAN: 'T CLASSES & INTERFACES Core interface which loads user-specific at, UserDetailsService (terface) An extension of the UserDetailsService ‘which provides the ability to create new isers and update existing ones, UserDetailsManager (interface) InMemoryUser Sample implementation classes ieee LaapUser DetallsManager eaz) bytes toadUserByUsename( Sting wernae) createLlser(UserDetaile wer) Updateser(UserDetals user) Aeletetser( Seng username) ‘hangePasrword(String oldPwd, Sting nome) eeeEait(String username) UserDetale All the above interfaces & classes uses an interface UserDetails & its implementation which provides core user information, J stNanel) ain) Fitri pee authenintedo setAuthetiated crete) USERDETAILS & AUTHENTICATION, eaz} RELATION BETWEEN THEM bytes Principal UserDeralls (nerttee) (Interface) Wy do we have «separate wap to store log wer deals “Authentication ser (lnterface) (Class) Y getPanevord) L % getUseramel) : Y fecluhorcis) (Cas) ¥ % ieebiedg See ea Authentication is the retum type in all the UserDetalls is the return type ina scenarios where we are trying to determine scenarios where we try to load the nser info if the authentication is successful oF not. from the storage systems. Like inside the Like inside the AuthenticationProvider & UserDetallsService & UserDetalls Manager AuthenticationManager AUTHENTICATION eazy USING JdbcUserDetailsManager bytes Instead of creating users inside the memory of web server, we can store them inside a DB and with the help of JdbcUserDetailsManager, we can perform authentication. public UserDetailsService userDetailsService(DataSource dataSource) { Please note to create table as per the return new JdbcUserDetailsManager(dataSource); JdbcUserDetailsManager class & insert user records inside them. NoOpPasswordEncoder is not recommended for prod apps. public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); USERDETAILSSERVICE IMPLEMENTATION FOR CUSTOM USER FETCHING LOGIC When we want to load the user details based on our own tables, columns, custom logic, then we need to create a bean that implements UserDetailsService and overrides the method loadUserByUsername() bytes Pur ire meta public UserDetoils loadUser8yUsername(String username) throws UsernameNotFoundException { Stri ee ast List«GrantedAuthority> authorities Pee er eee Coa aCe df eeu cet ree Sean oy userName = customer.get(0).getEmail( password = customer get(0) get? authorities = new ArrayListo() authorities add(new SimpleGrantedAuthority(customer.get(0).getRele())): RTL SEQUENCE FLOW bytes WITH OUR OWN USERDETAILSSERVICE IMPLEMENTATION Omnia eer Sag Sey Fe 2) ering a ie ae an ‘tose ch hein Uae ede nd The ate sje ised ewig py SEQUENCE FLOW WITH OUR OWN USERDETAILSSERVICE IMPLEMENTATION © terre tier ceteatas ‘UseraineParewordAuthenticationToken © srenenton Authentication Filters ‘RathovlaationFier Defeat ap inPugeOcnerstinetilte UsemamePaaswordAuthenticationF authenticated) @ <> Provider Manager wicied [Ome -<> hentieationProvider dondUertiyremamed @ |] @ vseera1s < authentication): tion object. We can Implement all our custom The authenticate() method receives and returns auth uthentication logi inside authentiate() method. ‘You'll implement e_The second method inthe AuthenticationProvider interface Is supports(Class authent tleathon object this method to return true I the current AuthenticationProvider supports the type of the Auth provided. SEQUENCE FLOW WITH OUR OWN AUTHENTICATIONPROVIDER IMPLEMENTATION ascend) Sag Seay Ptr “ponent 2) ar ing at se age Siete ne dea DB Ome he wer tasse Eiiniel oii tm ieee Uae ede nd {ye en ein ewig py SEQUENCE FLOW eaz! WITH OUR OWN AUTHENTICATIONPROVIDER IMPLEMENTATION bytes © x00: ver rte a ‘UseraineParewordAuthenticationToken @ srencenton authenticated) | oe. Fiters er Fae > Provider Manager DefaleLogin ea ratingFlier © Bepome UsemamePasswordAuthenticationFiiter aneninted @] | @ aun <requests Bate Car eure aig :. " Reece 5 )permit All) formLogin(Customizer.withDefaults()) -httpBasic(Customizer.withDefaults()): Pea a ert clos )): ).authenticated() eaz) CROSS-SITE REQUEST FORGERY (CSRF) bytes A typical Grose Site Request Forgery (CSRF or XSRF) attack aims to perform an operation in a web application on behalf of a user without their explicit cor n't directly steal the user's identity, but It explolts the user Co carry out an aetion without thelr will Consider you are using a website netflix.com and the attacker's website evil.com. Step 1: The Netflix user login to Netflix.com and the backend server of Netflix will provide a cookie which will store in the browser against the domata name Nerfis.com 8 ‘User subi his credentials & ty € login to Netfixcom ‘viLcom retums an web page which has x embedded ‘malicious link to change email of Nerlixvecount But Tn appears wid ext like "90% OFF on IPhone CROSS-SITE REQUEST FORGERY (CSRF) byte a Step 5 : User tempted and clicked on the malicious link which makes a request to Neils.com. And since the login cookie already present in the ‘same browser and the request o change email s being made fo the same domain Nerflix.com, the backend server of Netfix.com cant differentiate fiom where the request came, So here the evil.com forged the request as if itis coming fiom a Netfix.com UI page. User clicks oman en ae eee oe aera
OLUTION TO CSRF ATTACK byte S lefeat a SRF attack, applications need a way to determ Interface. The best way to achieve this is through a CSRF toker ‘The token needs to be Af the HTTP request is legitimately generated via the application's user A CSRF token is a secure random token that is used to prevent CSRF attacks, ique per user session and should be of Targe random value to “+ Let's see how this solve CSRF attack by taking the previous Netflix example again, ke i difficult to guess Step 1: The Netix user login to Netflix.com and the backend server of Netflix will provide a cookie which will store in the browser against the domain name Netfix.com along with « randomly generated unique CSRF token for this particular user session. CSRF token is inserted within hidden parameters of HTML forms to avoid exposure to session cookies see a onhie randomly generated CRE ‘Stop 2: The same Nethix user opens an evil.com website in another tab of the browser S LT ‘viLcom retums an web page which has x embedded ‘malicious link to change email of Nerlixvecount But Tn appears wid ext like "90% OFF on IPhone SOLUTION TO CSRF ATTACK byte s Step #2 User tempted and clicked on the malicious link which makes a request to Netfixcom. And since the login cookie already present in the ‘same browser and the request to change enait is being made (0 the same domain NetMis.com. This time the NetMis.com backend server expects CSRF token aloug with the cookie. The CSRF token must be same as inital value generated during login operation User cits on ask onevcom vile has content NL Boom i! The Netix throwed an evar 403 The CSRF token wil be ured bythe application server to verify the legitimacy of the end-user request fi Is coming trom che same App UL oF wo. The application server rejets the request i the SRF token al to DISABLE CSRF PROTECTION eazy INSIDE SPRING SECURITY ytés By default Spring Security block all HTTP POST, PUT, DELETE, PATCH operations with an error of 403, if there is no CSRF solution implemented insdie a web application. We can change this default behaviour by disabling the CSRF protection provided by Spring Security. Cog eer eet eae a ce en en ccs ant @ http.csrf((csrf) -> csrf.disable()) OTe e baile Ce eau te Uo Reet asst ere ‘ F ).authenticated() Ree aster 4 i ).permitAll()) Cater om ii ac) httpBasic(Customizer.withDefaults()): return http.build(); , With the given configuration of Spring Security, we can let the framework to generate a random CSRF token which can be sent to UI after successful login. The same taken need to be sent by UI for every subsequent requests it is making to backend. For certain paths, we can disable CSRF with the help of ignoringRequestMatchers. CSRF ATTACK SOLUTION eazy INSIDE SPRING SECURITY bytes aga Fi Ce SOA Re scoot ea aa ea a LC ea el eau pee on Sena nN ue http securityContext((context) -> context requireExplicitSave(alse)) ee ere a Cee ee ee eee ed a cee ees Ma) rs(corsCustomizer -> corsCustomizer.configurationSour: CorsConfigurationSource() (..})) era Me eu es ualpet OT ome (eae oa )outhenticated() requestMatchers( i b ).permitall()) formLogin(Customizer.withDefaults()) Deere rane Pet 0) sey 2 2 2 2 2 AUTHENTICATION & AUTHORIZATION DETAILS & COMPARISION AUTHENTICATION In authe he Mentity of users ane checked for providing the acess to the aystexn Authentication(AuthN) done before authorization Ie auth crvor response For example as a Rank customer/ order to perform actons i to prove our identity app, we need eaz) bytes worization, persons or users are cicked for accessing the resources Authovizaton(AuthZ) always happe after ses user's privilege or roles I authorizat ‘error response falls usually we ill get 405 Once logged into the appl z decide what kind of actions HOW AUTHORITIES STORED ? eazy INSIDE SPRING SECURITY bytes Authorities/Roles information in Spring Security is stored inside GrantedAuthority. There is only one method inside GrantedAuthority which return the name of the authority or role. SimpleGrantedAuthority is the default implementation class of GrantedAuthority interface inside Spring Security framework. rity implements Pate e ts eee Charo HOW AUTHORITIES STORED ? eaz} INSIDE SPRING SECURITY bytes Hom docs Authors information stored Inside the jets uring authentication of the wae ‘Authentication (Untertace) ‘UserDetails| (Interface) User (Class) (Class) y Y getAuthorities() getAuthorities() CONFIGURING AUTHORITIES byte Ss INSIDE SPRING SECURITY a In Spring Security the authorities requirements can be configured using the following ways, hasAuthority() — Accepts a single authority for which the endpoint wil be configured and eee eee mee cree ae ee eee eee ene eran Caen configured can invoke the endpoint. hasAnyAuthority() — Accepts multiple authorities for which the endpoint wil be ers having any of the configured and user will be validated against the authorities mentioned. Onl authority configured can invoke the endpoint. access() — Using Spring Expression Language (SpEL) I provides you unlimited posslbities eae arc nce cannon Se tN tee a ae Toe OR, AND inside acces) method. CONFIGURING AUTHORITIES INSIDE SPRING SECURITY See get et Rata ee ne eran ee ee ae eae te aera eee ne a ee eareria eaNG ) http.securityContext((context) -> context.requireExplicit Save(false)) Eee oC meee ae earch) fe eet eee eur au uta CorsConfigurationSource() (...})) oni Coupee ear oa eae alee arm scr an reese ae iC re AC Oe em a eae) addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.c ear oss eter Ge tean uests ener ec Oa een te. ac cin ate Dera aa Deut aaa Dee request Matchers('/user")authenticated() Cee ).permitallO) formLogin(Customizer.withDefaults()) Tra ote ace aera} return http.build() AUTHORITY vs ROLE eaz} INSIDE SPRING SECURITY bytes AUTHORITY Athorit slike an inividal ROLE ROLE isa group of vileges/actins es + Restricting access in a fine-grained Ex: VIEWACCOUNT, VIEWCARDS ec Restricting access in a coarse- eee Ex ROLE ADMIN, ROLE_USEI The names of the author Roles are also represented using the same cont ‘When defining a rol authority es/roles are arbitrary hi ‘tire and these names ean be customized as per the business requiren ract GrantedAuthority in Spring Security. its name should start with the ROLE_ prefix, This prefix specifies the difference between a role and an| CONFIGURING AUTHORITIES byte 'S INSIDE SPRING SECURITY a In Spring Security the ROLES requirements can be configured using the following ways, Has Role () ee secen ei tremianeletesree ions eet tend ecient te ener pneed eres “will be validated against the single role mentioned. Only users having the same role configured can invoke the endpoint. ras Ary Role |) peseeettimal rte ster ene erat ietenceetarinliteeeeseered andinre ‘will be validated against the roles mentioned. Only users having any of the role configured can call the endpoint access() — Using Spring Expression Language (SpEL) it provides you unlimited possibilities for configuring roles whieh are not possible with the above methods. We ean use operators like OR, AND inside access() method. Note : + ROLE_ prefix only to be used while confi fe the roles, we do it only by + access() method can be used not only for configuring authorization based on authority or role but also with any special requirements that we have. Far example we can configure access based on the country of the user or current time/date ing the role in DB. But when we configs CONFIGURING ROLES INSIDE SPRING SECURITY SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { CsrfTokenRequestAttributeHandler requestHandler = new CsrfTokenRequestAttributeHandler(): Perel pee oN ae 2p http.securityContext((context) -> context.requireExplicitSave(false)) sessionManagement(session -> session sessionCreationPolicy( SessionCreationPolicy. ALWA cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {..))) csrf((csrf) > csrf.csrfTokenRequestHandler( Pe Our ea esrf TokenRepository(CookieCerf TokenRepository.withHttpOnlyFalse())) Pr aman Ucn erm nO centr uu alc) authorizeHttpRequests((requests)-»requests eee Mein eee Dee ee reg Nene ee rea eg SIG authenticated() Re rear ia : 4 ).permitAll() Bae tc Mem rT) httpBasic(Customizer.withDefaults()) return http build(); FILTERS IN SPRING SECURITY byte Ss Lot of times we will have situations where we need to perform some house keeping activities duving the authentication and authorization low: Few such examples are, Input validation ‘Tracing, Auditing and reporting Logging of inpt lke IP Address ete Encryption and Decryption Mult factor authentication using OTP All such requirements can be handled using HTTP Filters inside Spring Security. Filters are servlet concepts which are leveraged in Spring Security as wel. We already saw some in built filters of Spring security framework like UsernamePassword AuthenticationFiltr, BasicAuthenticationFilter, DefaultLoginPageGeneratingFilter ete in the previous seetions AA filters a component which receives requests, process its logie and handover to the next filter in the chai. ‘Spring Security is based on a chain of servlet filters. Each filter has a specific responsibility and depending on the configuration, filters fare adeed or removed, We can add our custom filters as well based on the need. We can always check the registered filters inside S configurations, 1. @IERbLeWeBSEUHiEy(Hebg="EHIR)-- We need to enable the debugging of the security details }2. Enable logging of the details by adding the below property in ‘pplication properties ring Secutity with the below Jessie Pe ith Security that gets executed hi 1e authentleation flow, eaz) FILTERS IN SPRING SECURITY bytes Security filter chain: [ DisableEncodeU Filter WebAsyncManagerIntegrationFilter SecurityContextHolderFilter Header WsiterFter CorsFilter Cexlter Logoutfilter UsernamePasswordAuthentcationFilter DofaultLoginPageGeneratingFilter DefaultLogoutPageGeneratingFiter BasicAuthenticationFiter RequestCacheAwarcFiter SecurityContextHolderAwareRequestFilter AnonymousAuthenticationFilter SessionManagementFilter ExceptionTranslationFlter FiterSecurityinterceptor IMPLEMENTING CUSTOM FILTERS bytes INSIDE SPRING SECURITY We can create our own filters by implementing the Filter interface from the jakarta.rervlet package. Post that we need to override the doFilter() method to have our own custom logic. This method accepts 9 parameters the ServletRequest, ServletResponse and FilterChain, + ServietRequest 1 client represents the HTTP request, We use the ServletRequest object to retrieve details about the request from the ServletResponse—It represents the HTTP response, We nse the ServletResponse object to modify the response before sending it Ibaek tothe elien or further along the filter chain, + FilterChain—The filter chain represents a collection of filters with a defined order in which they act, We use the FilterChsin abject to forward the request to the next filter in the chain ¥ You can ada a new Filter to the spring security chain either before, after, or atthe position of « Known one. Fach position of the filter is an index (a numbes), and you might find it also referred to as “the order ¥ Below are the methods available to configure a custom filter in the spring security flow + addFilterBefore(Fiter, lass) ~ adds a filter before the position of the specified filter class + addFliterAfter({ilter, class) ~ adds a filter after the position of the specified filter class + addFiiterAt( filter, class) ~ adds a filter atthe location of the specified filter class ADD FILTER BEFORE IN SPRING SECURITY eaz) bytes ‘Ada lterBefore(fiter class) I will ad a Ser before the poston of the specified ier clas Request = CcatFilter (Order 2 ConsFter (Order 1) ‘RequestValidatonFilter (Onder 3) asicAuthentcaionFiter (Order 4) have the string “tet” inside i Here we ada filter ost Before authentication to write our own custom validation where the inp emi provided should not eaz) ADD FILTER AFTER bytes IN SPRING SECURITY suddFilterAfter{ filter class) ~1¢ will dd filter after the postion of the specified filter lass CcatFilter (Order2) | ee a ee ete ee eee eee of the logged in users ConsFlter (Order 1) Logging iter (Order 4) >| nasicauehentcstionFiler (Onder 3) ADD FILTER AT bytes IN SPRING SECURITY ad4FlicerAt(Ater, class) ~ Adis a filter at the locaton of the specified iter class. But the ender of the exceution ‘can't be guaranteed. This will not replace the filters already presenta the same order sicAuthentiationilter (Order 3) ‘CatFilter (Order 2) LoggingFilter (Order 8)? ‘Since we wil not have cantrolon the ade of the filters and itis random in nature we should avid providing the filters at same order OTHER IMPORTANT FILTERS bytes GenericFilterBean ae eate eet eee hich allows you to ase the initialization parameters and configurations deployment descriptors inside the OncePerRequestFilter Spring doesnt guarantee that your Siler will be calles only once Bat if swe havea scenario where we need to make sure to execute our Biter only conee then we can ds this ROLE OF TOKENS IN AUTHN & AUTHZ, eaz) bytes A Token can bea plain string of format universally unigue identifier (UID) oF it can be of type JSON Web Taken (JWT) axually that get generated when the user authenticated for che first time during logis, Se ee ee then validates the token and, if it's valid, returns the secure resource to the client. (Cent will receive the token, after secessful login in a Iheader/query string te (Client system has to make sure oct ‘onal the further request 10 the backend server sate token 1 Sd ‘ase /login with vsemame & password roan 27a Ticb-adel-0ananeta000 ‘Returns a token to the ellent aap ‘ox009nn¢-2752-11eb-ade1-0242%6120002 Token is Valid. Here are the ncoount details ‘Auth Server/App Auth Server/Appli foareetete same time I stores the token and client details inthe memory/DB, Se eee eee token, the server will valid token and retum the protected resources If ie isa val + + te tt ADVANTAGES OF TOKENS byte S ‘Token helps us not to share the credentials for every request Iti a security rsk to send credentials over the network frequentty. “Tokens can be imalidated during aay suspicious activities without iwalidating wer eredential, “Tokens can be erested with a short fe span. ‘Tokens can be 1d to store the user related information like roles/authorties ete, Rewsabitity ~ We eam have many separate servers, 1 authenticating the user me multiple platforms and domains, reusing the same token for Se less, easier to scale. The token contains al the information o identify the user, eliminating the need for the session state I we use load balancer, we can pass the ser to any server, instead of being bound to the same server we loge ‘We already used tokens inthe previous sections inthe form of CSRF and JSESSIONID tokens + CSRF Token protected our application from CSRF atecks + ISESSIONID is the default hen generated by the Spring Security which helped us no to share the redental to the backend every JWT TOKENS bytes ¥ JWT means JSON Web Token. It isa token implementation which will be in the JSON format and designed to use for the web requests, ¥ JWT is the most common and favorite token type that many systems use these days due to its special features and advantages, ¥ JWT tokens can be used both in the scenarios of Authorization Authentication along with Information exchange which means you can share certain user related data in the token itself which will reduce the burden of maintaining such details in the sessions on the server side. A JWT token has $ parts each separated by a period(.) Below is a sample JWT token, eyIhbGeiOiTUzLINilsInR5cClolkpXVCIo | ‘SWIG SRNTEANG MEMIDIGAY. SAK xwRISMeKKF2QT sfwpMedfsaPOkayIV_adQsswse 1. Header: 2. SRL 8. Signature (Optional) JWT TOKENS bytes ¥ Inside the JWT hs {nfo related to the token. If I chose to sign the token, the header contains the name of the algorithm that generates the signature. Baseé+ Encoded 328 IOUIL AT Nias CtotkpXVCID ¥ In the body, we ean store details related to user, roles ete. which ean be used later for AuthN and AuthZ. ‘Though there is no such limitation what we can send and how much we can send in the body, but we should put our best efforts to keep it as light as possible { Slolkp Bases Encode | eydnd WHOILAMJMONTYSODkwtiwibmF’ ED) 61 8 Gottivia WFoljosNTE2MIMSMDIyQ JWT TOKENS bytes ‘The last part of the token is the digital signature. This part can be optional if the party that you share the JWT token is internal and that someone who you can trust but not open in the web. But if you are sharing this token to the client applications which will be used by all the users in the open web then we need to make sure that no one changed the header and body values like Authorities, username ete. ‘To make sure that no one tampered the data on the network, we can send the signature of the content when initially the token is generated. To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. For example if you want to use the HMAC SHA256 algorithm, the signa way: -e will be created in the following ‘The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it ean also verify that the sender of the JWT is who it says it i. VALIDATION OF JWT TOKENS Signature eaz) bytes Hash that got generated based on basegs encoded v body and secret es of header, ‘Compte new Signsareore bash using dhe below formulae seeret (secton ete SERS HRIERRTIQTUR NPN aD Feuspare the hash vaio of the newly generated ‘hah with he hash already stored inside the SWT token Not Equal Equal JWT TOKENS byte se If you want to play with JWT tokens and put these concepts into practice, you ean use jwio debugger to decode, verif, and generate JWTs. eaz) METHOD LEVEL SECURITY bytes ¥ As of now we have applied authorization rules on the API paths/URLs using spring security but method level security allows to apply the authorization rules at any layer of an application like in service layer or repository layer ete, Method level security can be enabled using the annotation @EnableMethodSecurity on the configuration class, ¥ Method level security will also helps authorization rules even in the non-web applications where we will not have any endpoints, V Method level security provides the below approaches to apply the authorization rules and executing your business logic, + Invocation authorization ~ Validates if someone can invoke a method or not based on their roles/authorities + Filtering authorization — Validates what a method can receive through its parameters and what the invoker can receive back from the method post business logic execution, eaz) METHOD LEVEL SECURITY bytes Y Spring security will use the aspects from the AOP module and have the interceptors in between the method invocation to apply the authorization rules configured, ¥ Method level security offers below $ different styles for configuring the authorization rules on top of the methods, ost Authorize annotations + The prePostEnabled property enables Spring Security @PreAuthorize & + The securedEnabled property enables @Secured annotation + The jsr250Enabled property enables @RoleAllowed annotation ¥ @Sccured and @RoleAllowed are less powerful compared to @PreAuthorize and @PostAuthorize eaz) METHOD LEVEL SECURITY bytes + Using invocation authorization we can decide if a user is authorized to i before the method executes (preauthorizatio cr the method execution is completed (postauthorization). For filte efore calling the method we can use Prefiltering, bic class LoansServ @PreAuthorize("hasAuthority(VIEWLOANS)") (@PreAuthorize(*hasRole(ADMIN')) (@PreAuthorize(“hasAnyRole(ADMIN, USER’) ithenticatlon prinelpelusernatne") naan) { ‘return lomnaRepositorylondLoanDetailsByUserName(aseroame) eaz) METHOD LEVEL SECURITY bytes + For applying postauthorization rules below is the sample configuration, @sewiee public class LoaaService { G@PostAuthorize ("retumnObjectaysemame == auth public Loan getLoanDetails(St retui loanRepositoryloadLoanBy ser Name{usernatne complex authorization logi separate the logic using a separate class that implements PermissionEvaluator and overwrite the method hasPermission() inside it which can be leveraged inside the hasPermission configurations. eaz) METHOD LEVEL SECURITY bytes @RestController public class ContactContrller @PreFilter("ilterObject.contactName != Test") > saveContactlnguiryDetail @RequestBody List co eaz) METHOD LEVEL SECURITY bytes ring the parameters after executing the method we can use PostFilter annotation, But please note that the filterObject should be of type Collection interface. @PostFicen public List=C os PostFilter on the Spring Data repository ed data coming from the database. OAUTH2 INTRO TO OAUTH2 eaz} bytes PROBLEM THAT OAUTHs SOLVES te & Toitter App D Twiteer ser Y Scenario : The twitter user want to use an tied party website ca data present inside Twitter App. ‘TweetAnalyzer website that analyzes user tweets data and generates metrics from it lyzer, to get some insights about his tweets + With Out OAUTHS : Twitter user has to share his twitter account credentials to the TweetAnalyzer website. Using user credentials, the TweetAnalyzer website will iavoke the APIs of Twitter app Co fetch the tweet details and post that ‘generates a report for the end user. But it has a bigger disadvantage, the TweetAnalyzer can go fraud and make another operations on your behalf like change password, change email, make a rouge tweet ete + With OAUTH. : Twitter user doesn't have to share bis twitter account evedentials to the TweetAnaly2er website Instead he will et Twitter App to give a temporary access token to TweetAnalyzer with limited access like it can only reed the tweets data ‘With this approach, the TweetAnalyzer can only read the tweets data and i¢can'e perform any other operation, INTRO TO OAUTH2 PROBLEM THAT OAUTH2 SOLVES eaz) bytes fi axa betleving {your pinky promis credentials INTRO TO OAUTH2 bytes PROBLEM THAT OAUTH? SOLVES How come, Google let me Se all it’s p they are different webltea/ Appa? INTRO TO OAUTH2 PROBLEM THAT OAUTH? SOL} eaz) bytes If a Bank has multiple websites supporting accounts, loans, eards ete, With out OAuth, the Bank customers has to register and maintain different user profiles all the $ systems Even the AuthN & AuthZ logic, security standards will be duplicated in all the 8 websites. Any future changes or enhancements around security, authentication ete need to done in all the places eaz) INTRODUCTION TO OAUTH2 bytes Y¥ OAuth stands for Open Authorization. It's a free and open protocol, built on IETF standards and licenses from the Open Web Foundation ¥ OAuth 2.0 is a security standard where you give one application permission co access your data in another application The steps to grant permission, or consent, are often referred to as authorization or even delegated authorization ae tanec eee them your password Ceres See ete eee eee ee eee cere access to someone, without handing over full contra inthe form of the master key ‘The OAuth framework specifies several grant types for different use cases, n= well a8 framework for ereating new grant types. Authorization Code PKCE, Client Credentials Device Code Refresh Token Amplicit Flow (Legacy) Password Grant (Legacy) OAUTH2 TERMINOLOGY bytes Resource owner ~ It is you the end user: Inthe scenario of TweetAnalyzer the end user who want to use the ‘TweetAnalyzer website to get insights about this tweets. In other words, the end user owns the resources (Tweets), that why we call him as Resource owner Client — The TweetAnalyzer website isthe cient here as it isthe one which interacts with Twitter after taking Authorization Server — This is the server which knows about resource owner. In other words, resource owner should have an account in this server: In the scenario of TweetAnalyzer, the Twitter server which has authorization logie acts as Authorization server Resource Server — This is the server where the APIs, services that client want to consume are hosted. In the scenario of TweetAnalyzer, the Twitter server which has APIs like /getTweets etc, logic implemented. In smaller organizations, a single server can acts as both resource server and auth server Scopes — These are the granular permissions the Client wants, such as acess to data orto perform certain actions, In the scenario of TweetAnalyzer, the Auth server can issue an access token to client with the scope of only READ TWEETS. OAUTH2 SAMPLE FLOW ear bytes oestAnlrae em wil ech ou Lo wie ated expe tr interes in woking with them by llowng thir The Twitter eam collect the details loge et. fom TweetAnalyzer and inswed a CLIENT ID & CLIENT SECRET a Se eae ere Ce eae eas gueation, do T need te share my Tite setae tee The TweecAmayzer wei redinec the sel to Teter ‘button saying “Sigmup with Twitter” The end wer clicked on it and boom i has in poge OAUTH2 SAMPLE FLOW eaz) IN TWEETANALYZER SCENARIO [ACCESS & REFRESH tokens are random complex a The Tw eens Along the beceastoen ire ee eee eto enn ee fem the Auth sor ‘The Twitter resource server validates the acess coken with the Auth server nd fii valli return the resource comet Tweets data ise the respons ee et eee ete eee “hd i a th per a phy athe eines wth ut hain i ir THANKS To OAUTH © Ad OAUTH? FLOW 232 IN TIE AUTHORIZATION CODE GRANT TYPE tes curs suru seven s, Hello Auth Servers allow the cent o acess my terouree Here ey Cen, User allowed ou to aces hin resources Here AUTHORIZATION CODEL peer ete ereeare CODE, Pte rove mean sce tle OAUTH2 FLOW IN THE AUTHORIZATION CODE GRANT TYPE. eaz) bytes In the steps 2 & 5, where clint is making a request to Auth Server endpoint have to send the below: important details, + client_id ~ the id which identities the client application by the Auth Server. This will be granted when the client register fire tne with che Auth server + redirect_uri — the URI value which the Auth server needs to redirect post successful authentication, If default value is provided during the registration then this value is optional + scope — similar to authorities, Specifies level of access that client is requesting like READ + state —CSRF token value to protect from CSRF attacks + response_type - With the value ‘code’ which indicates that we want to follow authorization code grant ¥ Inthe atep 6 where client after received a authorization code from Auth server it will agsin make a request to Auth server far a token with the below valves, + code — the authorization code received from the above steps + client_id & client_secret ~ che client credentials which are registered with the auth server. Please note thae these are hot user eredentials + grant_type — With the value ‘authorization_code’ which identifies the kind of grant type is used + redirect_uri OAUTH2 FLOW IN THE AUTHORIZATION CODE GRANT TYPE. eaz) bytes Y We may wonder that why in the Authorization Code grant type client is making request 2 times to Auth server for authorization code and access token + In the first step, authorization server will make sure that user directly interacted with it along with the credentials, If the details are correct, auth server send the authorization code to client + Once it receives the authorization code, in this step client has to prove it’s identity along with the authorization code & client credentials to get the access token ¥ Well you may ask why can’t Auth server directly lub both the steps together and provide the token in a single step. The answer is that we used to have that grant type as well which is called as ‘implicit grant type’. But this grant type is not recommended to use due to it’s less secure. Hell Auth OAUTH2 FLOW IN THE IMPLICIT GRANT FLOW pts atow the into acess my resources. Here eee eee ase eaz) bytes =a =, eee _| ere ae te escurcesyoregpenee @ OAUTH2 FLOW eaz) IN THE IMPLICIT GRANT FLOW bytes Inthe step 5, where client is making a request to Auth Server endpoint, have to send the below important details, + client_id ~ the id which identifies che client application by the Auth Server. This will be granted when the client register first time with the Auth server + redirect_uri— the URI value which the Auth server needs to redirect post successful authentication, IF a default value is provided during the registration then this value is optional + scope ~ similar to authovities, Specifies level of access that clint i requesting like READ ‘+ state —CSRF token value to protect from CSRF attacks + response_type With the value ‘token’ which indicates that we want to follow implicit grant type If the user approves the request, the authorization server will redirect the browser back to the redireet_uvi specified by the application, adding a token and state to the fragment part of the URL. Implicie Grant flow is deprecated and is not recommended to use in production applications. Always use the Authorization code grant flow instead of implicit grant flow IN THE PASSWORD GRANT/RESOURCE OWNER CREDENTIALS GRANT TYPE AUTILSERVER a tredentils OAUTH2 FLOW Peseet eet eect ot the Une vert Hore the TOREM to sew the Fe ee Atha erver eaz) bytes a =, OAUTH2 FLOW IN THE RESOURCE OWNER CREDENTIALS GRANT TYPE eaz) bytes Y In the step 2, where client is making a request to Auth Server endpoint have to send the below important details, + client_id & client_secret ~ the credentials of the client to authenticate itself. + scope — similar to authorities + username & pa + grant_type — With the value ‘password’ which indicates that we want to follow password grant type pecifies level of access that client is requesting like READ sword ~ Credentials provided by the user in the login flow ¥ We use this authentication flow only if the client, authorization server and resource servers are maintained by the same organization ¥ This flow will be usually followed by the enterprise applications who want to separate the Auth flow and business flow. Once the Auth flow is separated different applications in the same organization can leverage it. OAUTH2 FLOW eaz) IN THE CLIENT CREDENTIALS GRANT TYPE bytes aun seem asounce maven = = vant to access protected reources Here ate eee eed ea ‘covrect Here isthe ACCESS TOKEN to ee eee eee eee ey Ciient. Your tokens valflated succenflly: Here are the esources you reuesied| OAUTH? FLOW eaz) IN THE CLIENT CREDENTIALS GRANT TYPE bytes Y In the step 1, where client is important details, king a request to Auth Server endpoint, have to send the below * client_id & client_seeret — the credentials of the client to authenticate itself, * scope ~ similar to authorities. Specifies level of access that client is requesting like READ * grant_type — With the value ‘elient_credentials’ which indicates that we want to follow client credentials grant type ¥ This is the most simplest grant type flow in OAUTH, Y We use this authentication flow only if there is no user and UI involved. Like in the scenarios where 2 different applications want to share data between them using backend APIs. eaz) OAUTH2 FLOW bytes IN THE REFRESH TOKEN GRANT TYPE a 10 access protected resources of the user: Heres the access token received in nl ser ogi n" Hey Auth Serva, need a ne acess token of the wer Ohssraeeeerey Hy Restos Serr, ant aces proeced neers Hees th aces on Hey Client. Your ten is aliflated successfully. Here are the esouces @) ot requested OAUTH? FLOW eaz) IN THE REFRESH TOKEN GRANT TYPE bytes ¥ In the step 5, where client is making a request to Auth Server endpoint have to send the below important details, + client_id & client_secret — the credentials of the client to authenticate itself, + refresh_token — the value of the refresh token received initially + scope ~ similar to authorities. Specifies level of access that client is requesting like READ + grant_type ~ With the value ‘refresh_token’ which indicates that we want to follow refresh token grant type ‘+ This flow will be used in the scenarios where the access token of the user is expired. Instead of asking the user to login again and again, we can use the refresh token which originally provided by the Authz server to reauthenticate the user. + Though we can make our access tokens to never expire but it is not recommended considering scenarios where the tokens can be stole if we always use the same token, + Even in the resource owner credentials grant types we should not store the user credentials for reauthentication purpose instead we should reply on the refresh tokens. USER (RESROUCE OWNER) RESOURCE SERVER TOKEN VALIDATION eaz) IN THE OAUTH2 FLOW USING DIRECT API CALL CLIENT, THOR] bytes IZATION ERVER Resource server validates the token every time by calling the AUTH server API for token validation RESOURCE SERVER RESOURCE SERVER TOKEN VALIDATION eaz) IN THE OAUTHe FLOW USING COMMON DB bytes om om AUTHORIZATION SERVER a bythe Auherver and che sone Do rae CENT] SX Pew, EEE caesnotiel OWNER) HE Tn Sen hey Shiny, com = ——] RESOURCE SERVER RESOURCE SERVER TOKEN VALIDATION byte S IN THE OAUTH? FLOW USING CERTIFICATES, AUTHORIZATION SERVER In this approach, there willbe no interaction b/w the Beer coe tetera Auth server and signature of it will be veried by ee etd USER (RESROUCE OWNER) CLIENT OPENID CONNECT WHAT IS OPENID CONNECT & WHY IT IS IMPORTANT ? ea: bytes What is OpenID Connect? + OpenlD Connect is a protocol that sits on top of the OAuth 2.0 framework. While OAuth 2.0 provides authorization via ‘an access token containing scopes, OpenID Connect provides authentication by introducing a new ID token which contains a new set of information and claims specifically for identity. ‘+ With the ID token, OpenID Connect brings standards around sharing identity details among the applications. | Sp Gans Authentication OAuth 2.0 Authorization OPENID CONNECT WHAT IS OPENID CONNECT & WHY IT IS IMPORTANT ? ea: bytes Why is OpenID Connect important? Identity is the key to any application. At the core of modern authorization is OAuth 2, authentication component. Implementing OpenID Connect on top of OAuth 9.0 completes an LAM (Identity & Access Management) strategy. [As more and more applications need to connect with each other and more identities are being populated on the internet, the ‘demand to be able to share these identities is also increased, With OpenID connect, applications can shave the identities easily and standard way. but OAuth 20 lacks an Authentication OpenID Connect Tdentity, ‘Access Management. OpenID Connect add below details to OAuth 2.0 1, OIDC standardizes the scopes to openid, profile, email, and address 2. ID Token using JWT standard 5. OIDC exposes the standardized “/userinfo" endpoint. IMPLEMENT OAUTH INSIDE EAZYBANK APP byte is USING KEYCLOAK AUTH SERVER We may have either Angular like Client App or REST API clients to get the resource defalls from resource server, both kinds we need to get access token from Auth Servers like KeyCloak 2. Once the access token received fro Auth Server cient Apps will connect ‘with Resource serve sccess token to get Accounts, Cards, Lo 5. Resource server wile Server to know the access token, server will respond with, client Apps Angular App ° OAUTH2 AUTH CODE FLOW WITH PROOF KEY FOR CODE EXCHANGE (PKCE) eaz) bytes ‘When public clients (eg, native and single-page applications) request Access Tokens, some additional security concerns ave posed that are not mitigated by the Authorization Code Flow alone, This is because public clients cannot secitely store & Cliene Secret Given these situations, OAuth 2.0 provides a version of the Authorization Code Flow for public client applications which males use of a Proof Key for Code Exchange (PKCE), The PKCE-enhanced Authorization Code Flow follows below steps, Once user clicks login, client app creates a cryptographically-random eode_verifier and from this generates s code_challenge. code challenge is a Bases4-URL-encoded string of the SHA856 hash of the code verifier + Redirects the user to the Authorization Server along with the code_challenge + Authorization Server stores the code_challenge and redirects the user back to the appli whieh is good for one use Client App sends the authorization cod and the code_verifier(created in step 1) to the Authorization Server. Authorization Server verifies the code_challenge and code_verfier If they are valid it vespond with 1D Token and ‘Access Token (and optionally, a Refresh Token). jon with an authorization code, OAUTH2 AUTH CODE FLOW eaz) bytes WITH PROOF KEY FOR CODE EXCHANGE (PKCE) ‘ey identity and ed nested by ey Cen, User allowed ou to aces hin resources Here AUTHORIZATION CODEL eee ete eee CODE Pee provide me tioken, sen om ath serer @) AUTILSERVER my a OAUTH2 AUTH CODE FLOW eZ WITH PROOF KEY FOR CODE EXCHANGE (PKCE) ytes ¥ Inthe steps 9 & 3, where client is making a request to Auth Server endpoint have to send the below important details, id — the id which identifies the client application by the Auth Server. This will be geanted when the client register first time with the Auth server + redirect_uri — the URI value which the Auth server needs to redirect post successful authentication, If default value 1 provided during the registration then this value is optional + scope ~ similar to authorities, Specifies level of access that client is requesting like READ + state — CSRF token value ro protect from CSRF attacks + response_type ~ With the valuc ‘code’ which indietes that we want to follow authorization cade grant + code_challenge - XXXXXX The code challenge generated as previously described + code_challenge_method - S256 (either plain or S256) ¥ Inthe atep 6 where client after received a authorization code from Auth server it will agsin make a request to Auth server far a token with the below valves, + code — the authorization code received from the above steps + client_id & client_seeret (optional) — the cieut credentials which are registered with the auth server, Please note that these are not user eredential + grant_type — With the value ‘authorization_code’ which identifies the kind of grant type is used + redirect_uri + code_verifier ~ The code verifier for the PKCE request, that the app originally generated before the authorization request

You might also like