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"
除了首先重定向到错误页面外,所有操作都正常工作。Hibernate:选择学生0。id为id1\u 1\u,学生0\u。以email2\u 1\u的形式发送电子邮件,学生0\u。姓名为姓名3\u 1\u,学生0\u。来自student student0的密码为password4\u 1\u其中student0\u。电子邮件=?Hibernate:选择角色0。学生id为学生1、2、0、角色0。角色id为角色id 2、角色2、角色0、角色1。id为id1\u 0\u 1\u,角色1\u。从角色0上的学生角色0内部加入角色1命名为名称2\u 0\u 1。角色id=角色1。角色0的id。学生id=?实体类
包装com.milton.tsi.model;
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;
}
}
存储库
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);
}
服务等级
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;
}
}
配置
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();
}
}
控制器
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";
}
}
登录表单
<!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>
http.csrf().disable().formLogin().permitAll().and().authorizeRequests().antMatchers("/login").permitAll().and().authorizeRequests().anyRequest().authenticated();
我使用的是Spring Security 4.1.1,但我遇到了一个问题:我试图访问URL,应用程序会重定向到登录页面。到现在为止,一直都还不错。 但是,成功登录后,应用程序会再次将我重定向到登录页面,并且不会创建任何会话,因此即使尝试直接访问URL(在URL栏中键入),应用程序也会重定向到登录页面。 有一些URL我必须要求登录才能访问它们。其他的,我可以访问无需身份验证。这些我不需要验证的URL
我现在一直在努力使用我的登录页面来让组件呈现Loggedin组件。我的前端是Reactjs,后端是NodeJS。我对nodejs、expression和react都是新手。 在loginform组件上,我使用fetch进行了一次post,它将用户名和密码传递给后端的相应endpoint。没问题。在后端,它读取我存储用户(不使用任何数据库)的jsonfile来查找匹配项,如果用户名和密码都匹配,则它
我正在尝试将Spring Security性与spring boot restful API集成。我的项目代码如下: web安全配置包括 你能帮我清理这个案子吗?
记录器文件中的日志- org.springframework.Security.Access.event.loggerlistener-安全授权失败,原因是:org.springframework.Security.Access.accessdeniedexception:访问被拒绝;通过身份验证的主体:org.springframework.security.authentication.ano
我在地址栏中输入的任何链接都会将我重定向到登录页面。我该怎么防止呢? 例如如果我加上http://localhost:8080/asdasdsa 我的安全配置:
我使用的是和和。一切都很好,但是当会话超时的时候,我会得到以下错误”,因为我已经在布局的main.gsp文件中调用了session变量。现在,我希望在每次会话超时后重定向到登录页面,并且不显示错误页面。要在会话超时后重定向,我已经在文件中这样做了 但是有这么多页,所以很难写每一页。还有其他的方法做这件事吗?请帮忙。