简体   繁体   English

提交Login spring引导项目时报错403

[英]Error 403 when I submit the Login spring boot project

I am trying to use spring security for the first time and i have a error.我第一次尝试使用 spring 安全性时出现错误。 It is saying 403 forbidding access.它说 403 禁止访问。 Here is my code:这是我的代码:

UserDetailsServiceImpl: 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 UserDetails 的 CustomDetailService

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 MyConfigClass 我已经设置了所有 bean

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:家庭电话 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这个 controller class 有 BCrypt 密码编码器

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.实际更改 Controller 中 user.setRole 中的角色对我有用。

 user.setRole("User"); 

to

 user.setRole("ROLE_USER");

and also do the user all charecters capital in MyConfig.java并在 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.您的配置 Class 应更改如下。

@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();
    
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM