[英]Spring Security. Login error
我是春季MVC和安全自動化的新手。 基本身份驗證都很好,但我想添加自定義身份驗證。 已將boot-secrity添加到gradle,將login.html頁面添加到具有2個輸入的模板中,使用帶有身份驗證規則的websecuritycinfig文件和到login.html的“登錄”映射
我對Spring Security自定義授權有疑問。 如果我輸入正確或錯誤的憑據,都將返回我登錄錯誤。 這是我的代碼。 請幫忙。 stackoverflow要求我添加更多描述。 這是我的代碼: WebSecurityConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
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;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
.permitAll();
}
@Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("qwerty").password("123").roles("ROLE");
}
}
}
login.html
<form th:action="@{/login}" method="post">
<div class="container">
<div class="alert alert-danger" th:if="${param.error}">
Invalid username and password.
</div>
<div class="form-group row">
<label for="login" class="col-sm-2 col-form-label">Логин</label>
<div class="col-sm-10" style="width: 100%; max-width: 500px;">
<input type="text" class="form-control" id="login" placeholder="Логин"/>
</div>
</div>
<div class="form-group row">
<label for="password" class="col-sm-2 col-form-label">Пароль</label>
<div class="col-sm-10" style="width: 100%; max-width: 500px;">
<input type="password" class="form-control" id="password" placeholder="Пароль"/>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Войти</button>
</div>
</div>
</div>
</form>
eSchoolController.java
import com.testgreetgo.eSchool.config.FlashMessage;
import com.testgreetgo.eSchool.dao.StudentDaoImpl;
import com.testgreetgo.eSchool.model.Student;
import com.testgreetgo.eSchool.service.StudentService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;
import javax.validation.Valid;
@Controller
public class eSchollController {
@Autowired
private StudentService studentService;
@RequestMapping(value="/login")
public String loginForm() {
return "login";
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/")
public String listStudents(ModelMap modelMap) {
List<Student> students = studentService.findAll();
modelMap.put("students", students);
return "home";
}
@RequestMapping(value = "/student/{id}")
public String studentDetails(@PathVariable Long id, ModelMap modelMap) {
Student student = studentService.findById(id);
modelMap.put("student", student);
return "student-detail";
}
//Add a student
@RequestMapping(value = "/students", method = RequestMethod.POST)
public String addStudent(@Valid Student student, BindingResult result, RedirectAttributes redirectAttributes) {
//Check if there errors on validation
if (result.hasErrors()) {
//Include valiation errors upon redirect
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.student", result);
//Add student if invalid was received
redirectAttributes.addFlashAttribute("student", student);
return "redirect:/students/add";
}
studentService.save(student);
redirectAttributes.addFlashAttribute("flash", new FlashMessage("Новый студент добавлен!", FlashMessage.Status.SUCCESS ));
return "redirect:/";
}
@RequestMapping(value="students/add")
public String formNewStudent(Model model) {
if (!model.containsAttribute("student")) {
model.addAttribute("student", new Student());
}
model.addAttribute("action", "/students");
model.addAttribute("submit", "Добавить");
return "form";
}
@RequestMapping(value="/students/{id}/edit")
public String formEditStudent(@PathVariable Long id, Model model) {
if (!model.containsAttribute("student")) {
model.addAttribute("student", studentService.findById(id));
}
model.addAttribute("action", String.format("/students/%s", id));
model.addAttribute("submit", "Сохранить");
return "form";
}
//Update an existing student
@RequestMapping(value="students/{id}")
public String updateStudent(@Valid Student student, BindingResult result, RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
//Include valiation errors upon redirect
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.student", result);
//Add student if invalid was received
redirectAttributes.addFlashAttribute("student", student);
return String.format("redirect:/students/%s/add", student.getId());
}
studentService.save(student);
redirectAttributes.addFlashAttribute("flash", new FlashMessage("Студент обновлен!", FlashMessage.Status.SUCCESS ));
return "redirect:/";
}
//Delete an existing student
@RequestMapping(value="/students/{id}/delete", method = RequestMethod.POST)
public String deleteStudent(@PathVariable Long id, RedirectAttributes redirectAttributes) {
Student student = studentService.findById(id);
studentService.delete(student);
redirectAttributes.addFlashAttribute("flash", new FlashMessage("Студент успешно удален!", FlashMessage.Status.SUCCESS));
return "redirect:/";
}
}
問題解決了。 如果有人需要:您需要告訴Spring Security將它們從受限資源中排除。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/javax.faces.resource/**");
}
如果問題仍然存在,請嘗試排除其他文件,例如
web.ignoring().antMatchers("/javax.faces.resource/**", "/custom.css", "/img/**");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.