简体   繁体   中英

Spring Security. Login error

i'm new in spring mvc and security autorization. All good with basic auth, but i want to add custom auth. Added boot-secrity to gradle, login.html page to templates with 2 inputs, websecuritycinfig file with auth rules and "login" mapping to login.html

I have problem with Spring Security custom authorization. If i enter right or wrong credentials, both return me login?error. Here is my code. Please help. stackoverflow asks me add more description. Here is my code: 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:/";
  }


}

Problem solved. If someone need: You need to tell Spring Security to exclude them from restricted resources.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/javax.faces.resource/**");
}

If problem is still there, try to exclude other files, like

web.ignoring().antMatchers("/javax.faces.resource/**", "/custom.css", "/img/**");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM