Spring Security JWT Authentication + PostgreSQL – RestAPIs SpringBoot + Spring MVC + Spring JPA
Java
package com.grokonez.jwtauthentication.model;
public enum RoleName {
ROLE_USER,
ROLE_PM,
ROLE_ADMIN
}
package com.grokonez.jwtauthentication.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.grokonez.jwtauthentication.security.jwt.JwtAuthEntryPoint;
import com.grokonez.jwtauthentication.security.jwt.JwtAuthTokenFilter;
import com.grokonez.jwtauthentication.security.services.UserDetailsServiceImpl;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true
)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private JwtAuthEntryPoint unauthorizedHandler;
@Bean
public JwtAuthTokenFilter authenticationJwtTokenFilter() {
return new JwtAuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
package com.grokonez.jwtauthentication.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.grokonez.jwtauthentication.model.Role;
import com.grokonez.jwtauthentication.model.RoleName;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(RoleName roleName);
}
package com.grokonez.jwtauthentication.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.hibernate.annotations.NaturalId;
@Entity
@Table(name = "users", uniqueConstraints = {
@UniqueConstraint(columnNames = {
"username"
}),
@UniqueConstraint(columnNames = {
"email"
})
})
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(min=3, max = 50)
private String name;
@NotBlank
@Size(min=3, max = 50)
private String username;
@NaturalId
@NotBlank
@Size(max = 50)
@Email
private String email;
@NotBlank
@Size(min=6, max = 100)
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {}
public User(String name, String username, String email, String password) {
this.name = name;
this.username = username;
this.email = email;
this.password = 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 getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
package com.grokonez.jwtauthentication.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@NaturalId
@Column(length = 60)
private RoleName name;
public Role() {}
public Role(RoleName name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public RoleName getName() {
return name;
}
public void setName(RoleName name) {
this.name = name;
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
package com.grokonez.jwtauthentication.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.grokonez.jwtauthentication.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
Also in Java:
- Title
- apt install java 11
- Category
- Java
- Title
- creating the functional interface in java
- Category
- Java
- Title
- java classes and methods simple logic with comments
- Category
- Java
- Title
- spigot kill entity
- Category
- Java
- Title
- java http interceptor
- Category
- Java
- Title
- convert list of integer to array in java
- Category
- Java
- Title
- how to find the total of the products added to the shopping cart in java program
- Category
- Java
- Title
- Error executing Maven. java.io.FileNotFoundException: The specified user settings file does not exist: /etc/java-8-openjdk
- Category
- Java
- Title
- java int to hex fixed length
- Category
- Java
- Title
- thread sleep java
- Category
- Java
- Title
- get drawable with string android java
- Category
- Java
- Title
- boolean java.lang.String.equals(java.lang.Object)' on a null object reference
- Category
- Java
- Title
- fragment manager in android
- Category
- Java
- Title
- what is java plug-in
- Category
- Java
- Title
- java string replace character at position
- Category
- Java
- Title
- how to interrupt a void java
- Category
- Java
- Title
- how to make an object move with arrow keys in java
- Category
- Java
- Title
- string to char in java
- Category
- Java
- Title
- string contains java
- Category
- Java
- Title
- java swing dialog box
- Category
- Java
- Title
- java delay
- Category
- Java
- Title
- Java loop throug gson JsonElement
- Category
- Java
- Title
- how to check wether the property exist in a object in java script
- Category
- Java
- Title
- java new string with values
- Category
- Java
- Title
- java execute jar from main
- Category
- Java
- Title
- are strings modifiable
- Category
- Java
- Title
- Compare integers java sort
- Category
- Java
- Title
- list in java
- Category
- Java
- Title
- how to write a perfect shuffle method in java
- Category
- Java
- Title
- how to initialize main in java
- Category
- Java
- Title
- shortcut to find a class in java project eclipse
- Category
- Java
- Title
- java set value of arraylist
- Category
- Java
- Title
- java constructor genertic
- Category
- Java
- Title
- strong password regular expression java
- Category
- Java
- Title
- count occurrences of character in string java 8
- Category
- Java
- Title
- absolute value in java
- Category
- Java
- Title
- get spring application context
- Category
- Java
- Title
- map java
- Category
- Java
- Title
- java nested for loop
- Category
- Java
- Title
- try block in java
- Category
- Java
- Title
- spring data jpa inheritance repository
- Category
- Java
- Title
- instantiate optinal java 8
- Category
- Java
- Title
- java min function
- Category
- Java
- Title
- change activity main drawer items text color programmatically android
- Category
- Java
- Title
- hide elements android
- Category
- Java
- Title
- pattern.compile java
- Category
- Java
- Title
- generate objects with for loop java
- Category
- Java
- Title
- int java
- Category
- Java
- Title
- how to compare current date and time with another date and time in android
- Category
- Java
- Title
- isnumber java
- Category
- Java
- Title
- java convert a char[] to string
- Category
- Java
- Title
- multiplication program java
- Category
- Java
- Title
- how to add all list elements at once in java
- Category
- Java
- Title
- javafx detect collision
- Category
- Java
- Title
- how to return the lower of two values in one line java
- Category
- Java
- Title
- string to arraylist convert java
- Category
- Java
- Title
- imageview.setbackground
- Category
- Java
- Title
- copy file with byte java
- Category
- Java
- Title
- java map foreach
- Category
- Java
- Title
- creating random color in java
- Category
- Java
- Title
- java iterate through hashmap
- Category
- Java
- Title
- array null pointer java
- Category
- Java
- Title
- validation list empty java
- Category
- Java
- Title
- Filebody in java
- Category
- Java
- Title
- method overloading
- Category
- Java
- Title
- public static void main(string args)
- Category
- Java
- Title
- room insert and return id
- Category
- Java
- Title
- java pass array as method parameter
- Category
- Java
- Title
- login and logout react native and firebase
- Category
- Java
- Title
- print values of bst java
- Category
- Java
- Title
- java for each
- Category
- Java
- Title
- java initialize string array
- Category
- Java
- Title
- integer to string java
- Category
- Java
- Title
- java letter alphabet index
- Category
- Java
- Title
- how to replace all of one character with nothing in java
- Category
- Java
- Title
- java timestamp
- Category
- Java
- Title
- FileNotFoundException: properties/fortunes.txt (No such file or directory)
- Category
- Java
- Title
- java find biggest number in array
- Category
- Java
- Title
- how do I change the opacity of a JButton
- Category
- Java
- Title
- find numbers in a string java
- Category
- Java
- Title
- bootstrap alert
- Category
- Java
- Title
- parallel sorting in java 8
- Category
- Java
- Title
- list java replace
- Category
- Java
- Title
- charat(0).touppercase() java
- Category
- Java
- Title
- java list as parameter
- Category
- Java
- Title
- absolute value java
- Category
- Java
- Title
- java get folder content
- Category
- Java
- Title
- programmation android avoir acces à la liste des intents de partage
- Category
- Java
- Title
- convert char to string java
- Category
- Java
- Title
- java get html from url
- Category
- Java
- Title
- java string split from input string
- Category
- Java
- Title
- how to ask user for his location in android
- Category
- Java
- Title
- abstract class in java
- Category
- Java
- Title
- java read file bufferedreader
- Category
- Java
- Title
- spigot actionbar
- Category
- Java
- Title
- android switch on change
- Category
- Java
- Title
- java string to integer
- Category
- Java
- Title
- change fab image programatically
- Category
- Java
- Title
- how to convert char to uppercase java
- Category
- Java
- Title
- unity how to make a gameobject slowly look at a position
- Category
- Java