总是重定向到登录?Spring授权错误

时间:2020-03-07 11:21:58

标签: java spring authorization

我正在尝试通过Spring进行授权。但是我的应用程序总是在/ login?error页面上重定向。尽管我输入了正确的用户名和密码。我使用NoOpPasswordEncoder.getInstance()在“ WebSecurityConfig”中的配置类中关闭了passwordencoder,但没有任何改变。

代码类“ WebSecurityConfig”:

package com.greatproject.dishonline.config;

//import com.greatproject.dishonline.entity.User;
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.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private DataSource dataSource;

    @Override

    protected void configure(HttpSecurity http) throws Exception {
       http.csrf().disable()
                .authorizeRequests()
                    .antMatchers("/", "/registration","/createUser","/sendEmail").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin().defaultSuccessUrl("/cabinet",true)/*.failureUrl("/invalidAuth")*/
                    .loginPage("/login")
                    .permitAll()
                .and()
                    .logout()
                    .permitAll();
    }
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

       auth.jdbcAuthentication()
               .dataSource(dataSource)
               .passwordEncoder(/*new MessageDigestPasswordEncoder("SHA-512")*/
                       passwordEncoder()
                       /*NoOpPasswordEncoder.getInstance()*/)
               .usersByUsernameQuery("select login, password from users where login=?")
             .authoritiesByUsernameQuery("select u.login, ra.roles from users u inner join role_auth ra on u.id = ra.id where u.login=?");

   }


    @Bean
    public PasswordEncoder passwordEncoder(){
        //return new
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

}

代码类“用户”:

package com.greatproject.dishonline.entity;

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

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Set;
import javax.persistence.*;

@Entity
@Table(name="Users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long ID;

    @Column
    private Long External_ID;

    @Column
    private String FirstName;

    @Column
    private String SecondName;

    @Column
    private String Email;

    @Column
    private String login;

    @Column
    private String password;

    @Column
    private String Phone;

    @Column
    private String Photo;

   /* @Column
    private Long ID_Role;*/

    public Set<RoleAuth> getRoles() {
        return roles;
    }

    public void setRoles(Set<RoleAuth> roles) {
        this.roles = roles;
    }

    @ElementCollection(targetClass = RoleAuth.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "role_auth", joinColumns = @JoinColumn(name = "id"))
    @Enumerated(EnumType.STRING)
    private Set<RoleAuth> roles;



    public User() {
    }

    public void setID_USER(Long ID) {
        this.ID = ID;
    }

    public void setExternal_ID(Long external_ID) {
        External_ID = external_ID;
    }

    public void setFirstName(String firstName) {
        FirstName = firstName;
    }

    public void setSecondName(String secondName) {
        SecondName = secondName;
    }

    public void setEmail(String email) {
        Email = email;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public void setPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        /*Password = password;
        byte[] dataPassword =  Password.getBytes("UTF-8");

        MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
        byte[] digest = messageDigest.digest(dataPassword);
        String buf = new String(digest,StandardCharsets.UTF_8);

        StringBuffer stringBuffer = new StringBuffer();

        for (byte bytes : digest) {
            stringBuffer.append(String.format("%02x", bytes & 0xff));
        }

        Password=stringBuffer.toString();*/

      //  MessageDigestPasswordEncoder MDPE=new MessageDigestPasswordEncoder("SHA-512");


      //this.password=MDPE.encode(password);
       this.password= new BCryptPasswordEncoder().encode(password);
        //this.password=password;

    }

    public void setPhone(String phone) {
        Phone = phone;
    }

    public void setPhoto(String photo) {
        Photo = photo;
    }



    public Long getID_USER() {
        return ID;
    }

    public Long getExternal_ID() {
        return External_ID;
    }

    public String getFirstName() {
        return FirstName;
    }

    public String getSecondName() {
        return SecondName;
    }

    public String getEmail() {
        return Email;
    }

    public String getLogin() {
        return login;
    }

    public String getPassword() {
        return password;
    }

    public String getPhone() {
        return Phone;
    }

    public String getPhoto() {
        return Photo;
    }



    @Override
    public String toString() {
        return "User{" +
                "ID=" + ID +
                ", External_ID=" + External_ID +
                ", FirstName='" + FirstName + '\'' +
                ", SecondName='" + SecondName + '\'' +
                ", Email='" + Email + '\'' +
                ", Login='" + login + '\'' +
                ", Password='" + password + '\'' +
                ", Phone='" + Phone + '\'' +
                ", Photo='" + Photo + '\'' +
              //  ", ID_Role=" + ID_Role +
                '}';
    }
}

代码枚举“ RoleAuth”:

package com.greatproject.dishonline.entity;

public enum RoleAuth {

    USER;
}

代码html页面“登录”:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Simple Login Form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style type="text/css">
        .login-form {
            width: 340px;
            margin: 50px auto;
        }
        .login-form form {
            margin-bottom: 15px;
            background: #f7f7f7;
            box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
            padding: 30px;
        }
        .login-form h2 {
            margin: 0 0 15px;
        }
        .form-control, .btn {
            min-height: 38px;
            border-radius: 2px;
        }
        .btn {
            font-size: 15px;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div class="login-form">
    <form action="/login" method="post">
        <h2 class="text-center">Log in</h2>
        <div class="form-group">
            <input type="text" class="form-control" name="login" placeholder="Login" required="required">
        </div>
        <div class="form-group">
            <input type="password" name="password" class="form-control" placeholder="Password" required="required">
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-block">Log in</button>
        </div>
        <div class="clearfix">
            <label class="pull-left checkbox-inline"><input type="checkbox"> Remember me</label>
            <a href="#" class="pull-right">Forgot Password?</a>
        </div>
    </form>
    <p class="text-center"><a href="#">Create an Account</a></p>
</div>
</body>
</html>

请帮助我解决此问题。

1 个答案:

答案 0 :(得分:0)

在您的configure方法中,参数顺序很重要。

您必须使用permitAll()定义所有授权路径(未经身份验证),之前,需要使用anyRequest().authenticated()进行身份验证的任何请求都是这样的:

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.csrf().disable()
        .formLogin().defaultSuccessUrl("/cabinet",true)
        .loginPage("/login").permitAll()
        .and()
        .logout().permitAll().and()
        .authorizeRequests()
        .antMatchers("/", "/registration","/createUser","/sendEmail").permitAll()
        .anyRequest().authenticated()
        .and()
        .build();
}

如果将它们放在后面,它将授权任何内容。

相关问题