Spring Security Cheetsheet
Spring Security Cheetsheet
---------------------------
@RestController
public class HelloController {
@GetMapping(path = "home")
public String home(){
return "home";
}
@GetMapping(path = "admin")
public String admin(){
return "admin";
}
@GetMapping(path = "mgr")
public String mgr(){
return "mgr";
}
@GetMapping(path = "clerk")
public String clerk(){
return "clerk";
}
}
Spring 2.7.11
--------------
@Component
@EnableWebSecurity
public class SecConfig extends WebSecurityConfigurerAdapter {
//auth: Who are u? 401
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("raj").password("raj123").roles("MGR")
.and()
.withUser("ekta").password("ekta123").roles("CLERK");
}
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();//hey dont expect passwould be
encr...
}
//authorization
//I know who are you but u dont hv acces to this resoucce 403
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/mgr/**").hasAnyRole("MGR")
.antMatchers("/clerk/**").hasAnyRole("CLERK","MGR")
.antMatchers("/home/**").permitAll()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ST
ATELESS);
}
}
@Component
@EnableWebSecurity
@EnableMethodSecurity
public class SecConfig {
@Bean
public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder){
UserDetails raj= User.withUsername("raj")
.password(passwordEncoder.encode("raj123"))
.roles("ADMIN")
.build();
UserDetails ekta= User.withUsername("ekta")
.password(passwordEncoder.encode("ekta123"))
.roles("MGR")
.build();
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws
Exception {
http.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(registry ->
registry.requestMatchers("/admin/**").hasAnyRole("ADMIN")
.requestMatchers("/mgr/**").hasAnyRole("ADMIN","MGR")
.requestMatchers("/clerk/**").hasAnyRole("ADMIN","MGR","CLERK")
.requestMatchers("/home/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.sessionManagement(httpSecuritySessionManagementConfigurer ->
httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy
.STATELESS));
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
step 3 a:
define user entity
---------------------
@Data
@NoArgsConstructor
@ToString
@Entity
@Table(name = "user_table_2")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="user_roles_2")
private List<String> roles= new ArrayList<>();
@Repository
public interface UserRepo extends JpaRepository<UserEntity, Integer> {
public UserEntity findByUsername(String userName);
}
@Service
@Transactional
public class UserServiceImpl implements UserService{
private UserRepo userRepo;
@Autowired
public UserServiceImpl(UserRepo userRepo) {
this.userRepo = userRepo;
}
@Override
public UserEntity findByUsername(String username) {
return userRepo.findByUsername(username);
}
@Override
public void addUserEntity(UserEntity userEntity) {
userRepo.save(userEntity);
}
}
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
UserEntity userEntity=userService.findByUsername(username);
if(userEntity==null)
throw new UsernameNotFoundException("Username/password is invalid");
//now problem: userEntity--->UserDetails(which spring sec understand)
return new SecUser(userEntity);
}
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<String> roles=userEntity.getRoles();
//somehow u need to createe AL to Array
String []rolesArray=roles.toArray(new String[roles.size()]);
return AuthorityUtils.createAuthorityList(rolesArray);
}
@Override
public String getPassword() {
return userEntity.getPassword();
}
@Override
public String getUsername() {
return userEntity.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
userService.addUserEntity(new UserEntity("raj",passwordEncoder.encode("raj123"),
List.of("ROLE_MGR","ROLE_CLERK")));
userService.addUserEntity(new UserEntity("ekta",passwordEncoder.encode("ekta123"),
List.of("ROLE_CLERK")));
@Componenthome
@EnableWebSecurity
public class SecConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private UserDetailsService userDetailsService;
@Component
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableMethodSecurity
public class SecConfig {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public AuthenticationProvider getAuthentication(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();//hey dont expect passwould be encr...
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
return http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STA
TELESS)
.and()
.build();
}
}
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoder;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtService {
public static final String
SECRET =
"5367566B59703373367639792F423F4528482B4D6251655468576D5A71347437";
Step 2: create an endpoint "authenticate" that allow user to get jwt token
-----------------------------------------------------------------------------
@RestController
public class HelloController {
@Autowired
private JwtService jwtService;
@Autowired
private AuthenticationManager authenticationManager;
@GetMapping(path = "home")
public String home() {
return "home ";
}
//3. craete a endpoint so that user can send his u/p and get token
@PostMapping(path = "authenticate")
public String authenticateAndGetToken(@RequestBody AuthRequest authRequest) {
Authentication authentication
=authenticationManager.
authenticate(new UsernamePasswordAuthenticationToken(
authRequest.getUsername(),
authRequest.getPassword()
));
if(authentication.isAuthenticated()){
return jwtService.generateToken(authRequest.getUsername());
}else {
throw new UsernameNotFoundException("user is invalid");
}
@PreAuthorize("hasAuthority('ROLE_MGR')")
@GetMapping(path = "mgr")
public String mgr(){
return "mgr ";
}
@PreAuthorize("hasAuthority('ROLE_MGR') or hasAuthority('ROLE_CLERK')")
@GetMapping(path = "clerk")
public String clerk(){
return "clerk ";
}
@Service
public class JwtAuthFilter extends OncePerRequestFilter {
@Autowired
private JwtService jwtService;
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {
if(username!=null &&
SecurityContextHolder.getContext().getAuthentication()==null){
UserDetails
userDetails=userDetailsService.loadUserByUsername(username);
//username is correct , and we are going to get UNAuthToeken and put
that in SecurityContextHolder ....
if(jwtService.validateToken(token, userDetails)){
UsernamePasswordAuthenticationToken authToken=
new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
// authToken.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
filterChain.doFilter(request, response);
}
}
@Component
@EnableWebSecurity(debug = true)
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableMethodSecurity
public class SecConfig {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtAuthFilter jwtAuthFilter;