Skip to content

Commit

Permalink
Implement Authorization using Authorities,Roles
Browse files Browse the repository at this point in the history
  • Loading branch information
eazybytes committed Sep 20, 2022
1 parent 5eeaafe commit 9b53360
Show file tree
Hide file tree
Showing 22 changed files with 341 additions and 296 deletions.
8 changes: 2 additions & 6 deletions section7/springsecsection7/pom.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
Expand All @@ -12,7 +12,7 @@
<artifactId>springsecsection7</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springsecsection7</name>
<description>Demo project for Spring Boot</description>
<description>Demo project for Spring Boot and Spring Security</description>
<properties>
<java.version>17</java.version>
</properties>
Expand Down Expand Up @@ -62,10 +62,6 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
// Optional
@EnableJpaRepositories("com.eazybytes.repository")
@EntityScan("com.eazybytes.model")
public class EazyBankBackendApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ private List<GrantedAuthority> getGrantedAuthorities(Set<Authority> authorities)

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,43 @@

import java.util.Collections;


@Configuration
public class ProjectSecurityConfig {

@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowCredentials(true);
config.setAllowedHeaders(Collections.singletonList("*"));
config.setMaxAge(3600L);
return config;
}
}).and().csrf().ignoringAntMatchers("/contact").csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and().authorizeRequests()
/*.antMatchers("/myAccount").hasAuthority("VIEWACCOUNT")
.antMatchers("/myBalance").hasAnyAuthority("VIEWACCOUNT","VIEWBALANCE")
.antMatchers("/myLoans").hasAuthority("VIEWLOANS")
.antMatchers("/myCards").hasAuthority("VIEWCARDS")*/
.mvcMatchers("/myAccount").hasRole("USER")
.antMatchers("/myBalance").hasAnyRole("USER","ADMIN")
.antMatchers("/myLoans").hasRole("ADMIN")
.antMatchers("/myCards").hasRole("USER")
.antMatchers("/user").authenticated()
.antMatchers("/notices", "/contact").permitAll()
.and().httpBasic()
.and().formLogin();
return http.build();
}
@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
http.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowCredentials(true);
config.setAllowedHeaders(Collections.singletonList("*"));
config.setMaxAge(3600L);
return config;
}
}).and().csrf().ignoringAntMatchers("/contact","/register").csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and().authorizeRequests()
/*.antMatchers("/myAccount").hasAuthority("VIEWACCOUNT")
.antMatchers("/myBalance").hasAnyAuthority("VIEWACCOUNT","VIEWBALANCE")
.antMatchers("/myLoans").hasAuthority("VIEWLOANS")
.antMatchers("/myCards").hasAuthority("VIEWCARDS")*/
.antMatchers("/myAccount").hasRole("USER")
.antMatchers("/myBalance").hasAnyRole("USER","ADMIN")
.antMatchers("/myLoans").hasRole("USER")
.antMatchers("/myCards").hasRole("USER")
.antMatchers("/user").authenticated()
.antMatchers("/notices","/contact","/register").permitAll()
.and().formLogin()
.and().httpBasic();
return http.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@

@RestController
public class AccountController {
@Autowired
private AccountsRepository accountsRepository;
@GetMapping("/myAccount")
public Accounts getAccountDetails(@RequestParam int id) {
Accounts accounts = accountsRepository.findByCustomerId(id);
if (accounts != null ) {
return accounts;
}else {
return null;
}
}

@Autowired
private AccountsRepository accountsRepository;

@GetMapping("/myAccount")
public Accounts getAccountDetails(@RequestParam int id) {
Accounts accounts = accountsRepository.findByCustomerId(id);
if (accounts != null ) {
return accounts;
}else {
return null;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@
@RestController
public class BalanceController {

@Autowired
private AccountTransactionsRepository accountTransactionsRepository;
@Autowired
private AccountTransactionsRepository accountTransactionsRepository;

@GetMapping("/myBalance")
public List<AccountTransactions> getBalanceDetails(@RequestParam int id) {
List<AccountTransactions> accountTransactions = accountTransactionsRepository.
findByCustomerIdOrderByTransactionDtDesc(id);
if (accountTransactions != null ) {
return accountTransactions;
}else {
return null;
}
}
@GetMapping("/myBalance")
public List<AccountTransactions> getBalanceDetails(@RequestParam int id) {
List<AccountTransactions> accountTransactions = accountTransactionsRepository.
findByCustomerIdOrderByTransactionDtDesc(id);
if (accountTransactions != null ) {
return accountTransactions;
}else {
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@

@RestController
public class CardsController {
@Autowired
private CardsRepository cardsRepository;
@GetMapping("/myCards")
public List<Cards> getCardDetails(@RequestParam int id) {
List<Cards> cards = cardsRepository.findByCustomerId(id);
if (cards != null ) {
return cards;
}else {
return null;
}
}

@Autowired
private CardsRepository cardsRepository;

@GetMapping("/myCards")
public List<Cards> getCardDetails(@RequestParam int id) {
List<Cards> cards = cardsRepository.findByCustomerId(id);
if (cards != null ) {
return cards;
}else {
return null;
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@
@RestController
public class ContactController {

@Autowired
private ContactRepository contactRepository;

@PostMapping("/contact")
public Contact saveContactInquiryDetails(@RequestBody Contact contact) {
contact.setContactId(getServiceReqNumber());
contact.setCreateDt(new Date(System.currentTimeMillis()));
return contactRepository.save(contact);
}
@Autowired
private ContactRepository contactRepository;

public String getServiceReqNumber() {
Random random = new Random();
int ranNum = random.nextInt(999999999 - 9999) + 9999;
return "SR"+ranNum;
}
@PostMapping("/contact")
public Contact saveContactInquiryDetails(@RequestBody Contact contact) {
contact.setContactId(getServiceReqNumber());
contact.setCreateDt(new Date(System.currentTimeMillis()));
return contactRepository.save(contact);
}

public String getServiceReqNumber() {
Random random = new Random();
int ranNum = random.nextInt(999999999 - 9999) + 9999;
return "SR"+ranNum;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@

@RestController
public class LoansController {
@Autowired
private LoanRepository loanRepository;
@GetMapping("/myLoans")
public List<Loans> getLoanDetails(@RequestParam int id) {
List<Loans> loans = loanRepository.findByCustomerIdOrderByStartDtDesc(id);
if (loans != null ) {
return loans;
}else {
return null;
}
}

@Autowired
private LoanRepository loanRepository;

@GetMapping("/myLoans")
public List<Loans> getLoanDetails(@RequestParam int id) {
List<Loans> loans = loanRepository.findByCustomerIdOrderByStartDtDesc(id);
if (loans != null ) {
return loans;
}else {
return null;
}
}

}
Original file line number Diff line number Diff line change
@@ -1,31 +1,60 @@
package com.eazybytes.controller;


import java.security.Principal;
import java.util.List;

import com.eazybytes.model.Customer;
import com.eazybytes.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eazybytes.model.Customer;
import com.eazybytes.repository.CustomerRepository;
import java.sql.Date;
import java.util.List;

@RestController
public class LoginController {

@Autowired
private CustomerRepository customerRepository;

@RequestMapping("/user")
public Customer getUserDetailsAfterLogin(Principal user) {
List<Customer> customers = customerRepository.findByEmail(user.getName());
if (customers.size() > 0) {
return customers.get(0);
}else {
return null;
}

}
@Autowired
private CustomerRepository customerRepository;

@Autowired
private PasswordEncoder passwordEncoder;

@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody Customer customer) {
Customer savedCustomer = null;
ResponseEntity response = null;
try {
String hashPwd = passwordEncoder.encode(customer.getPwd());
customer.setPwd(hashPwd);
customer.setCreateDt(String.valueOf(new Date(System.currentTimeMillis())));
savedCustomer = customerRepository.save(customer);
if (savedCustomer.getId() > 0) {
response = ResponseEntity
.status(HttpStatus.CREATED)
.body("Given user details are successfully registered");
}
} catch (Exception ex) {
response = ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An exception occured due to " + ex.getMessage());
}
return response;
}

@RequestMapping("/user")
public Customer getUserDetailsAfterLogin(Authentication authentication) {
List<Customer> customers = customerRepository.findByEmail(authentication.getName());
if (customers.size() > 0) {
return customers.get(0);
} else {
return null;
}

}

}
Loading

0 comments on commit 9b53360

Please sign in to comment.