Пользователь не вышел из системы при использовании реакции и весенней загрузки. - PullRequest
0 голосов
/ 19 марта 2019

У меня возникает эта ошибка, когда при переходе по URL-адресу "/ logout" он не удаляет сеанс и перенаправляет меня на "/" вместо "/ login"

Это настройки, которые у меня есть

Router.js

export default (onLogout) => (
    <Route path="/" name="app" component={App}>
        <IndexRoute component={privateRoute(SimpleListComponent)}/>
        <Route path="private" component={privateRoute(PrivatePage)}/>
        <Route path="login" component={loggedInRedirectRoute(LoginPage)}/>
        <Route path="register" component={loggedInRedirectRoute(RegisterPage)}/>
        <Route path="logout" onEnter={onLogout}/>
    </Route>
);

Итак, роутер настроен в файле index.js. Это передает функцию onLogout, которая по сути является Authenticator.logout ()

У меня проблема в том, что не похоже, что вызывается метод выхода из системы. Когда я выполняю проверку сети xhr, я не вижу вызова для удаления сеанса.

Authenticator.js

export function logout() {
    return {
        types: [LOGOUT, LOGOUT_SUCCESS, LOGOUT_FAIL],
        promise: (client) => client.delete('/api/session'),
        afterSuccess: () => {
            localStorage.removeItem('auth-token');
        }
    };
}

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

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/api/session").permitAll()
            .antMatchers("/api/register").permitAll()
            .antMatchers(HttpMethod.GET, "/api/**").authenticated()
            .antMatchers(HttpMethod.POST, "/api/**").hasRole("ADMIN")
            .antMatchers(HttpMethod.PUT, "/api/**").hasRole("ADMIN")
            .antMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
            .and()
            .requestCache()
            .requestCache(new NullRequestCache())
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
            .and().csrf().disable();
    }

AuthenticationResource.java

@RestController()
@RequestMapping("/api/session")
public class AuthenticationResource {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody ServerResult<User> login(@RequestBody Credentials credentials, HttpSession httpSession) {
        ServerResult<User> serverResult;
        Authentication authentication = new UsernamePasswordAuthenticationToken(credentials.getEmail(), credentials.getPassword());
        try {
            SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(authentication));
        } catch (BadCredentialsException e) {
            serverResult = new ServerResult<>(ErrorMessage.BAD_CREDENTIALS.getMessage(), Severity.Exception);
            return serverResult;
        } catch (Exception e) {
            serverResult = new ServerResult<>(ErrorMessage.GENERIC_ERROR.getMessage(), Severity.Exception);
            return serverResult;
        }

        return addUserToSession(httpSession, userService, credentials.getEmail());
    }

    @RequestMapping(method = RequestMethod.GET)
    public User session(HttpSession session) {
        return (User) session.getAttribute("user");
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public void logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
    }
}

Итак, мое понимание таково: Url обращается к бэкэнд-коду вместо прохождения маршрута, он обращается к конфигурациям безопасности и на самом деле не вызывает метод js onLogout и удаляет сеанс. Что мне здесь не хватает? Почему я не могу выйти успешно?

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