在使用oAuth2的Spring-Boot中请求异步angularJs期间的会话范围问题

问题描述 投票:2回答:1

我有一个很奇怪的问题。在简单的项目中,我将Spring-Boot与oAuth2配合使用(这正是jhipster生成的项目)。

在服务中,我通过restTemplate类与远程控制器(远程API)连接。然后,我创建了一个特殊的类来存储对远程API的cookieSession访问(此类具有Session范围)。

在授权过程中,我将cookieSession从远程API保存到Session Scope类,然后在向远程API的其他部分发出请求时,使用此seesionCookie。

问题是,当我从AngulrJS发出异步请求时,有时Session范围类存在,有时它没有数据(为空),但是当我刷新网站时,我有了此数据(不进行下一次授权)。我发出同步请求没有问题。

@Service
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AuthorizationOsipDataService implements Serializable {
    private String cookieSession;

    public String getCookieSession() {
        return cookieSession;
    }

    public void setCookieSession(String cookieSession) {
        this.cookieSession = cookieSession;
    }
}

服务:

@Service
public class OsipService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private AuthorizationOsipDataService authorizationOsipDataService;

    public String signInToOsipAndGetCookieSession (String login, String password) throws SignInToOsipException {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("j_username", login);
        map.add("j_password", password);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map, new HttpHeaders());
        log.debug("Logging... user: '{}'", login);
        ResponseEntity response = restTemplate.exchange(osipUrl + authorizationUrl, HttpMethod.POST, requestEntity, String.class);
        if(isLogged(response)){
            String cookieSession = response.getHeaders().getFirst(HttpHeaders.SET_COOKIE);
            log.debug("Succes login, setting authorizationOsipDataService");
            authorizationOsipDataService.setPassword(password);
            authorizationOsipDataService.setUsername(login);
            authorizationOsipDataService.setCookieSession(cookieSession);
            selectCompanyContext("538880bde511f776304687e6");
            if(hasRoleOsipLite().getBody()){
                return cookieSession;
            } else {
                throw new SignInToOsipException("User doesn't has ROLE_OSIPLITE");
            }
        } else{
            throw new SignInToOsipException("Login error, HttpSatus:"+ response.getStatusCode().toString());
        }

    }

    private boolean isLogged(ResponseEntity response){
        //if location contains '/signin', it means that there is redirect and signin is failed
        return !response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("osip/signin");
    }

    public ResponseEntity selectCompanyContext(String companyContextId){
        HttpHeaders httpHeaders = makeHeadersWithJson();
        HttpEntity<String> requestEntity = new HttpEntity<String>(httpHeaders);
        log.debug("Selecting context... '{}' ", companyContextId);
        return restTemplate.exchange(osipUrl + selectCompanyContextUrl + companyContextId, HttpMethod.GET, requestEntity, String.class);
    }

    public ResponseEntity<NipExistDTO> isExistNip(String nip){
        HttpHeaders httpHeaders = makeHeadersWithJson();
        HttpEntity<String> requestEntity = new HttpEntity<String>(httpHeaders);
        log.debug("isExistTest for nip: '{}'", nip);
        return restTemplate.exchange(osipUrl + existNipUrl + nip, HttpMethod.GET, requestEntity, NipExistDTO.class);
    }
}

.........

控制器:

@RestController
@RequestMapping("/customer")
public class CustomerResource {

    private final Logger log = LoggerFactory.getLogger(CustomerResource.class);

    @Autowired
    private OsipService osipService;

    @RequestMapping(value = "nipExist", method = RequestMethod.GET)
    public
    @ResponseBody
    ResponseEntity<NipExistDTO> isNipExist(@RequestParam String nip) throws SignInToOsipException {
        return osipService.isExistNip(nip);
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public
    @ResponseBody
    ResponseEntity addCustomer(@RequestBody NewCustomerDTO newCustomerDTO) throws SignInToOsipException {
        return osipService.addCustomerToOsip(newCustomerDTO);

    }


}

WebConfig(会话范围的配置)

 public void onStartup(ServletContext servletContext) throws ServletException {
        log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
        EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
        if (!env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
            initMetrics(servletContext, disps);
        }
        if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
            initCachingHttpHeadersFilter(servletContext, disps);
            initStaticResourcesProductionFilter(servletContext, disps);
            initGzipFilter(servletContext, disps);
        }
        log.info("Web application fully configured");
        servletContext.addListener(new RequestContextListener());
    }

AngularJS

angular.module('osipliteApp')
    .controller('CustomerController', function ($rootScope, $scope, Upload, $timeout,Customer,Scenario,Dictionary,$loading,$state,Auth) {
        $loading.start('addCustomer');
        $scope.isCollapsed=true;

        //**** Initializing fields ****//
        $scope.customerDTO = {name: null, nip: null, street: null,streetNumber:null, postOffice:null, zipCode:null, phoneNumber1: null, surveyNotes:null};
        $scope.personEditDTO = {name: null, email:null,code1:null, phone1:null};
        $scope.newCustomerDTO = {customerType: null, scenarioId:null};
        $scope.personEditDTO.code1= '+48';
        $scope.customerTypes = [{name:"Osoba fizyczna",value:"NATURAL_PERSON"},{name:"Jednostka budżetowa",value:"BUDGETARY_UNITS"},{name:"Spółka prawa handlowego",value:"COMMERCIAL"},{name:"Osoba fizyczna prowadząca działalność gospodarczą",value:"NATURAL_PERSON_WITH_BUSINESS"}];
        $scope.products = Dictionary.get({dictionaryCode: 'PRODUCT_TYPE',languageCode:"PL"},function(success){
            $scope.scenariosList = Scenario.get({value:'active'},function(success){$loading.finish('addCustomer');},function(error){restErrorHandler(error);});
        },function(error){restErrorHandler(error);});

        $scope.clear = function () {
            $scope.customerDTO = {name: null, nip: null, street: null,streetNumber:null, postOffice:null, zipCode:null, phoneNumber1: null, surveyNotes:null};
            $scope.personEditDTO = {name: null, email:null,code1:"+48", phone1:null};
            $scope.newCustomerDTO = {customerType: "NATURAL_PERSON", scenarioId:null};
            $scope.nipInvalid = null;
            $scope.nipExist = null;
            clearSurvey();
        };
...
...
java angularjs spring spring-boot jhipster
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.