Giter Club home page Giter Club logo

spring-security-starter's Introduction

Spring Authentication & Authorization Without JWT

Background

...

Spring Frameworks

  • Spring Web
  • Spring Security
  • Spring Data MongoDB
  • Lombok

To Get Started

setup

clone this git repository into your local folder

git clone [email protected]:omgshalihin/spring-security-starter.git

go into the folder and open with your favorite IDE (intelliJ)

cd <folder> && idea pom.xml

inside main/resources, create a file called env.properties and then update the MongoDB Atlas connection string

DB_USER=<mongoDB_user>
DB_PWD=<mongoDB_password>
DB_ENDPOINT=<mongoDB_endpoint>
DB_NAME=<mongoDB_name>

create user and store into database

POST http://localhost:8080/users/new

  • JSON body example
{
    "username" : "shalihin",
    "password" : "password",
    "email" : "[email protected]",
    "roles" : "role_admin,role_user"
}
  • expected output
User [shalihin] has been added to the database

Create a new class called SecurityConfig and annotate the class with the following:

  • @Configuration
  • @EnableWebSecurity
  • @EnableMethodSecurity

Reading Username/Password: Form Login

  • config/SecurityConfig.java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http.csrf().disable()
        .authorizeHttpRequests()
        .requestMatchers("/users/new", "/products/welcome").permitAll()
        .and()
        .authorizeHttpRequests().requestMatchers("/products/**")
        .authenticated().and().formLogin().and().build();
}

Password Storage: Custom data stores with UserDetailsService

  • config/SecurityConfig.java
@Bean
public UserDetailsService userDetailsService() {
    return new DatabaseUserDetailsService();
}
  • config/DatabaseUserDetailsService.java
@Component
public class DatabaseUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<UserModel> userModel = userRepository.findUserModelByUsername(username);
        return userModel.map(UserModelUserDetails::new)
                .orElseThrow(() -> new UsernameNotFoundException(String.format("User [%s] not found", username)));
    }
}
  • config/UserModelUserDetails.java
public class UserModelUserDetails implements UserDetails {

    private String username;
    private String password;
    private List<GrantedAuthority> authorities;

    public UserModelUserDetails(UserModel userModel) {
        username = userModel.getUsername();
        password = userModel.getPassword();
        authorities = Arrays.stream(userModel.getRoles().split(","))
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Password Storage: Password Encoder

  • config/SecurityConfig.java
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

Password Storage: DaoAuthenticationProvider

  • config/SecurityConfig.java
@Bean
public AuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setUserDetailsService(userDetailsService());
    authenticationProvider.setPasswordEncoder(passwordEncoder());
    return authenticationProvider;
}

Expression-Based Access Control:

  • controller/ProductController.java OR controller/UserController.java
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@PreAuthorize("hasAuthority('ROLE_USER')")

spring-security-starter's People

Contributors

omgshalihin avatar

Stargazers

 avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.