在angular和Spring应用程序中,我的注销功能不起作用?

时间:2018-11-02 10:35:25

标签: java angular spring-boot spring-security spring-session

在春季会议中,我使用过redis服务器。 现在我正在使用Angular 7。

此处代码 1> nav-compo.ts   单击注销按钮后,函数直接调用此处logout()

constructor(
  private readonly api: ApiService,
  private readonly modalService: BsModalService,
) {
}

@ContentChild(MyComponent) myComp: MyComponent;

onClick(){
  this.api.getData().subscribe(data => {
    this.data$.next(data);

    this.modalService.show(this.myModal);  

    // not sure if it's already available here, or you need to wrap it in a setTimeout...    
    const comp = this.myComp;
  });
}

2>此处loginService

 logout()
  {


    this.loginService.logout().subscribe(
      res =>
      {
        location.reload();
      },

      err =>
      {
        console.log(err);
      }
    )

  }

3>最后一个后端部分(LoginResource)

import { MyAccountComponent } from './../components/my-account/my-account.component';
import { AppConst } from './../constants/app-const';
import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';


@Injectable()
export class LoginService {

   private serverPath:string =AppConst.serverPath;

  constructor(private http: HttpClient, private router:Router) { }

  sendCredential(username: string, password: string) {
    let url = this.serverPath+'/token';
    let encodedCredentials = btoa(username+":"+password);
    let basicHeader = "Basic "+encodedCredentials;
    let headers = new HttpHeaders ({
        'content-Type' : 'application/x-www-form-urlencoded',
        'Authorization' : basicHeader
      });


    return this.http.get(url,{headers:headers});

  }


  checkSession(){
    let url = this.serverPath+'/user/checkSession';
    let headers = new HttpHeaders ({
        'x-auth-token' : localStorage.getItem('xAuthToken')

    });
    console.log("Value of token at check Session ",localStorage.getItem('xAuthToken'));
    return this.http.get(url,{responseType:'text'});
  }

    logout(){
      let url = this.serverPath+'/user/logoutUser';
      let headers = new HttpHeaders ({
        'x-auth-token' : localStorage.getItem('xAuthToken')

      });
      return this.http.post(url,'',{responseType:'text'});
     // return this.http.post(url,'',{headers:headers});

    }




    ngOnInit() {
      //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
      //Add 'implements OnInit' to the class.

    }

}

4>过滤器类

package com.bookstore.resource;

import java.util.Collections;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginResource {

    @RequestMapping("/token")
    public Map<String,String> token(HttpSession session,HttpServletRequest req){

        System.out.println(req.getRemoteHost());

        String remoteHost=req.getRemoteHost();
        int port =req.getRemotePort();

        System.out.println("This is remoteHost:Port Number"+remoteHost+":"+port);
        System.out.println("This is GetRemoteAddr"+req.getRemoteAddr());

        return Collections.singletonMap("token",session.getId());


    }


    @RequestMapping("/user/checkSession")
    public ResponseEntity checkSession()
    {

        System.out.print(HttpStatus.OK);

        return new ResponseEntity("Session Activated!",HttpStatus.OK);
    }

    @RequestMapping(value="/user/logoutUser",method=RequestMethod.POST)
    public ResponseEntity logout()
    {
        SecurityContextHolder.clearContext();
        System.out.println("louout");
        return new ResponseEntity("Logout done",HttpStatus.OK);
    }



}
  • 单击注销按钮后,我的页面将重新加载,但发生了。它与上一页相同。

  • 如果我将{headers:headers}作为回报,请退出loginservice.logout() 那么错误就会出现

package com.bookstore.config;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class RequestFilter implements Filter{



    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-auth-token");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        System.out.println("value of request "+request.getMethod());
        if(!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
            System.out.println("At if");
            try {
                chain.doFilter(req, res);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Pre-fight");
            response.setHeader("Access-Control-Allowed-Methods", "POST, GET, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, x-auth-token, " +
                    "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}


}
     

(http.js:167)           在HttpHeaders.push ../ node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach中   (http.js:236)           在Observable._subscribe(http.js:1436)           在Observable.push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable._trySubscribe中   (Observable.js:43)           在Observable.push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable.subscribe   (Observable.js:29)           在subscribeTo.js:21           在subscriptionToResult(subscribeToResult.js:11)

1 个答案:

答案 0 :(得分:0)

您已获得以下用于注销的代码:

SecurityContextHolder.clearContext();

我原本希望这样:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){    
    new SecurityContextLogoutHandler().logout(request, response, auth);
}

请明确说明,这不是路由问题还是权限问题?您确实看到服务器端确实到达了'/ user / logoutUser'RequestMapping吗?