春季安全。登录错误

时间:2018-01-05 11:44:19

标签: java spring security login

我是春季mvc和安全自动化的新手。基本身份验证都很好,但我想添加自定义身份验证。添加boot-secrity到gradle,login.html页面添加到带有2个输入的模板,带有auth规则的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:/";
  }


}

1 个答案:

答案 0 :(得分:0)

问题解决了。如果有人需要:您需要告诉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/**");