有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在每次重定向到错误页面时登录到我的spring启动项目

>;我遇到的错误

    i am trying to login in my spring boot project .it logged in by getting data from database but every time it first redirect to the error page and i got this error..
    timestamp   "2020-01-16T18:08:34.995+0000"
        status  999
        error   "None"
        message "No message available"

every thing works fine except it redirect to error page first.Hibernate: select student0_.id as id1_1_, student0_.email as email2_1_, student0_.name as name3_1_, student0_.password as password4_1_ from student student0_ where student0_.email=? Hibernate: select roles0_.student_id as student_1_2_0_, roles0_.role_id as role_id2_2_0_, role1_.id as id1_0_1_, role1_.name as name2_0_1_ from student_role roles0_ inner join role role1_ on roles0_.role_id=role1_.id where roles0_.student_id=? entity class

包裹通讯。米尔顿。tsi。模型

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
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.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column
    @NotEmpty
    private String name;
    @Column
    @Email(message = "Enter a valid email")
    @NotEmpty
    private String email;
    @Column
    @NotEmpty(message = "Enter password please")
    private String password;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "student_role",joinColumns = {@JoinColumn(referencedColumnName = "id",name = "student_id")},
    inverseJoinColumns = {@JoinColumn(referencedColumnName = "id",name = "role_id")})
    private List<Role>roles;

    public Student(long id, @NotEmpty String name, @Email @NotEmpty String email, @NotEmpty String password,
            List<Role> roles) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        this.password = password;
        this.roles = roles;
    }

    public Student() {
        super();
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    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 List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }


}
package com.milton.tsi.model;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Role {

    @Id
    private long id;
    private String name;
    @ManyToMany(mappedBy = "roles")
    private List<Student>students;


    public Role() {
        super();
    }
    public Role(long id, String name, List<Student> students) {
        super();
        this.id = id;
        this.name = name;
        this.students = students;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }


}

repository

package com.milton.tsi.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.milton.tsi.model.Student;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long>{
    Optional<Student>findByEmail(String email);

}

service class

package com.milton.tsi.service;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.milton.tsi.model.Student;
import com.milton.tsi.repository.StudentRepository;

@Service
@Transactional
public class StudentService implements UserDetailsService{

    @Autowired
    private StudentRepository studentRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Student student = studentRepository.findByEmail(username).orElseThrow(()->new UsernameNotFoundException(username+" not found"));
        return new User(student.getEmail(),student.getPassword(),getAuthorities(student));
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Student student) {
        String[]roles= student.getRoles().stream().map((role)->role.getName()).toArray(String[]::new);
        Collection<GrantedAuthority>authorities =AuthorityUtils.createAuthorityList(roles);
        return authorities;
    }


}

configuration

package com.milton.tsi.configuration;

import javax.sql.DataSource;

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.builders.WebSecurity;
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;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
    @Autowired
    private DataSource dataSource;
    @Autowired
    UserDetailsService studentService;

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



        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //auth.jdbcAuthentication().dataSource(dataSource);
            auth.userDetailsService(studentService)
            .passwordEncoder(passwordEncoder());
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.headers().frameOptions().sameOrigin()
            .and()
            .authorizeRequests()
            .antMatchers("/","/about").permitAll()
            .antMatchers("/static/**","/resources/**","/css/**","/webjars/**").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            //.defaultSuccessUrl("/")
            .failureUrl("/error/403.html").permitAll()
            .and()
            .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/?logout")

            .and()
            .exceptionHandling();
        }


        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring()
            .antMatchers("/static/**","/resources/**","/css/**","/webjars/**");
        }
    }


package com.milton.tsi.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;

@Configuration
public class WebmvcConfig  implements WebMvcConfigurer{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
     registry.addViewController("/").setViewName("views/home");
     registry.addViewController("/login").setViewName("/login");
     registry.addViewController("/admin/home").setViewName("adminhome");
    registry.addViewController("/about").setViewName("/views/about");
    }

    @Bean
    public SpringSecurityDialect springSecurityDialect()
    {
        return new SpringSecurityDialect();
    }
}

controller

package com.milton.tsi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class AdminController {

@RequestMapping("/admin/home")
public String adminHome() {
    return "adminhome";
}
}
package com.milton.tsi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {

    @RequestMapping("/")
    public String home() {
        return "home";
    }

    @RequestMapping("/about")
    public String about() {
        return "views/about";
    }

}
package com.milton.tsi.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController {

@RequestMapping("/user")
public String studentHome() {
    return "studenthome";
}
}

login form

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorate="~{layout}">
<head>
<meta charset="ISO-8859-1">
<style type="text/css">

fieldset {
    width: 450px;
    border: 5px solid #D82128;
    border-radius: 5px;
    margin-top: 150px;
    margin-bottom: 20px;
    text-align: right;
    padding: 50px;
    padding-right: 80px;
    margin-left: 450px;
}

legend {
    width: 250px;
    border: 1px solid #D82128;
    border-radius: 5px;
    background-color: #D82128;
    text-transform: uppercase;
    text-align: center;
    color: white;
}

</style>
</head>
<body>
    <div layout:fragment="content">

        <fieldset class="card" style="border-color: #D82128">
            <legend>Login</legend>
            <form  th:action="@{/login}" method="post">
            <div th:if="${param.error}"><h3>Invalid email or password</h3></div>
                <div>
                    <input type="email" name="username" placeholder="enter email">
                </div>
                <div>
                    <input type="password" name="password" placeholder="enter password">
                </div>
                <div>
                    <button class="btn btn-warning">Login</button>
                </div>

            </form>
        </fieldset>

    </div>
</body>
</html>

共 (1) 个答案

  1. # 1 楼答案

    http.csrf().disable().formLogin().permitAll().and().authorizeRequests().antMatchers("/login").permitAll().and().authorizeRequests().anyRequest().authenticated();