Постмаппинг в Spring Security - PullRequest
       0

Постмаппинг в Spring Security

0 голосов
/ 12 февраля 2019

Я уже сделал процесс аутентификации (используя оба: inMemoryAuthentication и jdbcAuthentication).Он отлично работает для всех пользователей, которые я вставляю в базу данных вручную.На следующем шаге я пытаюсь сделать простой процесс регистрации, но метод PostMapping моего контроллера не позволил мне получить логин и пароль пользователя.Проблема возникает, только если не войти в систему как для другой учетной записи.Когда я использую метод / createUser как зарегистрированный пользователь, он отлично работает

Это мой контроллер

@Controller
public class MainController {
@RequestMapping("/register")
    public String createNewUser() {
        System.out.println("register method");
        return "register";
    }

    @PostMapping("/createUser")
    public String afterUserCreation(HttpServletRequest request) {
        System.out.println("start method");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmedPassword = request.getParameter("confirm_password");
        System.out.println("user: "+username + " pass: "+password+ " confirm: "+confirmedPassword);
        return "login";
    }
}


It's my Spring Security configuration

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("User").password("USER").roles("USER")
        .and().withUser("Admin").password("ADMIN").roles("ADMIN");

        auth.jdbcAuthentication().dataSource(dataSource)
        .passwordEncoder(new BCryptPasswordEncoder())
        .usersByUsernameQuery("select username, password, TRUE as enabled from auth_user_data where username=?")
        .authoritiesByUsernameQuery("select username, role from auth_user_data where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login","/register").permitAll()
        .antMatchers("/addNew").hasRole("ADMIN")
        .antMatchers("/*").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
        .anyRequest().authenticated() 
        .and().formLogin().loginPage("/login").failureUrl("/login")
        .and().exceptionHandling().accessDeniedPage("/accessDenied")
        ;
    }
}

My HTML page:

<h1>Registr user:</h1>
        <form th:action="@{/createUser}" method="post">
            <label for="username">Username</label>: <input type="text"
                id="username" name="username" autofocus="autofocus" /> <br />
            <label for="password">Password</label>: <input type="password"
                id="password" name="password" /> <br />
            <label for="confirm_password">Confirm password</label>: <input type="password"
                id="confirm_password" name="confirm_password"/> <br />
            <input type="submit" value="Create account" />
        </form>

Я ожидаю получить имя пользователя и пароль в моем методе

1 Ответ

0 голосов
/ 12 февраля 2019

Изменить

    .antMatchers("/login","/register").permitAll()

на

   .antMatchers("/login","/register","/createUser").permitAll()

allowAll сообщает Spring Security, что для доступа к этому URL-адресу не требуется проверка подлинности.Этот URL / createUser в вашем случае.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...