Поддержка страницы входа в Spring Security - PullRequest
0 голосов
/ 03 апреля 2020

Я пытался настроить это должным образом, однако у меня возникли некоторые трудности, и я считаю, что это небольшое исправление, которое я не вижу. Страница входа в систему безопасности Spring по умолчанию работает просто отлично, но я не могу настроить пользовательский html для отображения. Он просто читает преобразование get «login» в виде строки. Любая помощь будет принята с благодарностью!

1. Конфигурация безопасности

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService myUserDetailsServices;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsServices);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().
        authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").hasAnyRole("ADMIN", "USER")
                .antMatchers("/").permitAll()
                .and().formLogin()
                    .loginPage("/login")
                    .permitAll();
    }


    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

}

3. Основной контроллер

@RestController
@CrossOrigin(origins="http://localhost:4200")
public class MainController {

    private UserRepository userRepository;
    private UserDetailsService myUserDetailsServices;

    public MainController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/")
    public String home() { return ("<h1>Welcome</h1>");
    }

    @GetMapping("/login")
    public String login() { return ("login");
    }

    @GetMapping("/user")
    public String user() {
        return ("<h1>Welcome User</h1>");
    }

    @GetMapping("/admin")
    public String admin() {
        return ("<h1>Welcome Admin</h1>");
    }

    @GetMapping("/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();

4.login. html

<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
<head>
    <title tiles:fragment="title">Login</title>
</head>
<body>
<div tiles:fragment="content">
    <form name="f" th:action="@{/login}" method="post">
        <fieldset>
            <legend>Please Login</legend>
            <div th:if="${param.error}" class="alert alert-error">
                Invalid username and password.
            </div>
            <div th:if="${param.logout}" class="alert alert-success">
                You have been logged out.
            </div>
            <label for="username">Username</label>
            <input type="text" id="username" name="username"/>
            <label for="password">Password</label>
            <input type="password" id="password" name="password"/>
            <div class="form-actions">
                <button type="submit" class="btn">Log in</button>
            </div>
        </fieldset>
    </form>
</div>
</body>
</html>

Ответы [ 4 ]

0 голосов
/ 05 апреля 2020

Я полагаю, что это исправит проблему, если вы просто попробуете.

authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").hasAnyRole("ADMIN", "USER")
                .antMatchers("/").permitAll()
                .and()   
                .formLogin().loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/index.html",true);

Кроме того, сама система безопасности Spring имеет конечную точку URL-адреса сопоставления / login, и если вы хотите изменить ее, тогда используется метод loginProcessingUrl. помогает изменить путь входа в систему

0 голосов
/ 03 апреля 2020

Я понял это. Я добавил этот ModelAndView в мой основной класс контроллера, и он исправил это. Спасибо за предложения, хотя.

    @RequestMapping("/login")
public ModelAndView login () {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("login");
    return modelAndView;
}
0 голосов
/ 03 апреля 2020
0 голосов
/ 03 апреля 2020

Ваша страница входа в систему /login.html не / login

, поэтому ваша конфигурация должна быть:

.formLogin().loginPage("/login.html").permitAll()
.loginProcessingUrl("/login")
.defaultSuccessUrl("/index.html",true);

, а также отображение / login в контроллере. удалите это из MainController:

 @GetMapping("/login")
    public String login() { return ("login");
    }
...