I am trying to use spring security for the first time and i have a error. It is saying 403 forbidding access. Here is my code:
UserDetailsServiceImpl:
package org.springboot.security;
import org.springboot.dao.UserRepo;
import org.springboot.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class UserDetailsServiceImpl implements UserDetailsService{
@Autowired
private UserRepo repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user=repo.getUserByUsername(username);
if(user==null) {
throw new UsernameNotFoundException("User was null");
}
CustomUserDetails customUserDetails = new CustomUserDetails(user);
return customUserDetails;
}
}
CustomDetailService which UserDetails
package org.springboot.security;
import java.util.Collection;
import java.util.List;
import org.springboot.entities.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class CustomUserDetails implements UserDetails{
private User user;
public CustomUserDetails(User user) {
super();
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority =new SimpleGrantedAuthority(user.getRole());
return List.of(simpleGrantedAuthority);
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
MyConfigClass where I have set all my beans
package org.springboot.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter{
@Bean
public UserDetailsService getUserDetailService() {
return new UserDetailsServiceImpl();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(this.getUserDetailService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("Admin")
.antMatchers("/user/**").hasRole("User")
.antMatchers("/**").permitAll()
.and().formLogin()
.and().csrf().disable();
}
}
Home Controller:
package org.springboot.controller;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springboot.dao.UserRepo;
import org.springboot.entities.User;
import org.springboot.helper.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HomeController {
@Autowired
private BCryptPasswordEncoder encoder;
@Autowired
private UserRepo repo;
@RequestMapping("/")
public String home(Model model) {
model.addAttribute("title", "Home Page | Smart Contact Manager");
return "home";
}
@RequestMapping("/about")
public String about(Model model) {
model.addAttribute("title", "About Page | Smart Contact Manager");
return "about";
}
@RequestMapping("/register")
public String register(Model model) {
model.addAttribute("title", "Sign Up | Smart Contact Manager");
model.addAttribute("user",new User());
return "register";
}
@PostMapping("/do_register")
public String registerUser(@Valid @ModelAttribute("user") User user,BindingResult results,
@RequestParam(value = "agreement", defaultValue = "false") boolean agreement,
Model model, HttpSession session)
{
try {
if(!agreement) {
System.out.println("Check the agreement checkbox to continue");
throw new Exception("Check the agreement checkbox to continue");
}
if(results.hasErrors()) {
model.addAttribute("user",user);
return "register";
}
model.addAttribute("user", user);
user.setRole("User");
user.setEnable(true);
user.setImageUrl("default.png");
user.setPassword(encoder.encode(user.getPassword()));
User result=this.repo.save(user);
System.out.println(result);
model.addAttribute("user", user);
session.setAttribute("message",new Message("Successfullly registered!!", "alert-primary"));
return "register";
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("user", user);
session.setAttribute("message",new Message("Something went wrong!!"+e.getMessage(), "alert-danger"));
}
return "register";
}
}
This controller class has BCrypt Password Encoder
Please help me solve this error!
Try changing this in your Security Config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("Admin")
.antMatchers("/user/**").hasRole("User")
.anyRequest().permitAll() // <------- Here is the change
.and().formLogin()
.and().csrf().disable();
}
Actuall Changing the role in user.setRole in home Controller worked for me.
user.setRole("User");
to
user.setRole("ROLE_USER");
and also do the user all charecters capital in MyConfig.java
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/**").permitAll()
.and().formLogin()
.and().csrf().disable();
Your Config Class should be changed as follows.
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.cors().and().csrf().disable();
http.headers().frameOptions().disable();
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/register").permitAll()
.anyRequest().authenticated()
.and().formLogin();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.