Cara Membuat Basic Auth di java spring

Hallo guys, kali ini saya akan mempraktikan cara membuat basic auth di java spring. Tutorial ini menggunakan framework spring boot. Basic auth pada tutorial ini menggunakan cookies dan data username password disimpan di dalam database. Baiklah sedikit menjelaskan tentang apa itu session dan cookies.

SESSION AND COOKIES
  • Session: Session adalah pertukaran informasi sementara dan interaktif antara dua atau lebih perangkat komunikasi atau antara komputer dan pengguna.
  • Cookies: Cookies adalah bagian kecil data yang dikirim dari situs web dan disimpan di komputer pengguna oleh browser web pengguna saat pengguna sedang menjelajah.
Metode Penyimpanan
  • Session: Session disimpan di sisi server.
  • Cookies: Cookies disimpan di browser klien sebagai file teks.


Basic Auth in Database

Mari langsung saja kita praktikan cara membuat basic auth di java spring

Tambahkan depedency di pom.xml


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>



File CustomWebSecurityConfigureAdapter.java
package com.enigma.config;
import com.enigma.service.CustomDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigureAdapter extends WebSecurityConfigurerAdapter {
    @Autowired
    CustomDetailService userDetailService;
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
        http.formLogin();
        http.logout().logoutUrl("/logout").invalidateHttpSession(true).deleteCookies("JSESSIONID");
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
     auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
  }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

Controller
package com.enigma.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AuthenticationController {

    @GetMapping("/login")
    public void login(){

    }

}

Entity

package com.enigma.entity;

import org.hibernate.validator.constraints.UniqueElements;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Email;

@Entity
@Table(name = "mst_user")
public class User {
    @Id
    private String id;
    @Column(unique = true)
    @UniqueElements
    private String username;
    @Email
    private String email;
    private String password;

    public User(String id, @UniqueElements String username, @Email String email, String password) {
        this.id = id;
        this.username = username;
        this.email = email;
        this.password = password;
    }

    public User() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}


exception
package com.enigma.Exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotResponse extends RuntimeException{
}


Repository

package com.enigma.repositories;

import com.enigma.entity.Song;
import com.enigma.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserRepository extends JpaRepository<User,String> {
    public User findUserByUsername(String keyword);

}


Service Implement

package com.enigma.service;

import com.enigma.Exception.UserNotResponse;
import com.enigma.entity.User;
import com.enigma.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class CustomDetailService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //yng entity
        User userFound = userRepository.findUserByUsername(username);
        if (userFound==null){
            throw  new UserNotResponse();
        }
        //karena namanya sama ini manggil di paket
        return new org.springframework.security.core.userdetails.User(userFound.getUsername(),userFound.getPassword(),new ArrayList<GrantedAuthority>());
    }
}

Setting aplication.properties

server.port=7070

##
spring.datasource.url=jdbc:postgresql://localhost:5432/artis_management
spring.datasource.username=postgres
spring.datasource.password=enigmacamp

#spring.profiles.active=test

spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

optional !
Tambahan untuk mengenerate password karena belum ada fitur register, kemudian hasil data generate di simpan kedalam database.

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class Main {
    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("indra"));
    }
}


Kemudian save di database


Testing aplikasinya




Kemudian coba log out dengan mengetik url di bawah ini

Selamat mencoba ^-^

1 Response to "Cara Membuat Basic Auth di java spring"

  1. As alluded to earlier, the South Korean government implements strict gambling laws, making it troublesome for any particular person to participate in or patronize on-line casinos. With the government of South Korea being unable to dam access to worldwide on-line casinos effectively, many are optimistic that the business will continue rising in 온라인카지노 the country. While the government of South Korea may have been profitable in regulating the country's gambling business, on-line casinos have been challenging this technique considerably. The government has constantly warned towards on-line casino gaming, prosecuting those discovered guilty to the fullest extent of the regulation. Online slots are now are|are actually} equipped with a number of the} greatest mind-blowing modern themes, making them among the many most loved by each on-line and land-based on line casino players.

    ReplyDelete

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel