Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to pass an Authorization header to server sent events from Angular JS. As i am not currently getting any header details so, spring SecurityContextHolder.getContext().getAuthentication() is always null and giving nullPointerException. Please provide the solution so that I can get user context in java layer.

What I have tried:

I need to pass an Authorization header to server sent events from Angular JS. As i am not currently getting any header details so, spring SecurityContextHolder.getContext().getAuthentication() is always null and giving nullPointerException. Please provide the solution so that I can get user context in java layer.
Posted
Updated 23-Sep-16 2:47am

1 solution

Since you didn't post any of your angular code I'm going to make some assumptions (ex: using basic auth + get call).

For $http.get there is a headers property that you should be able to use.

JavaScript
$http.get('< your url here >' {
    headers: {'Authorization': 'Basic < your auth string here >'}
});


If that doesn't meet your needs I encourage you to use google to find something. Authentication and requests done via angular is well documented.

Auth example

Google - Angular auth header
 
Share this answer
 
v2
Comments
vani sharma 27-Sep-16 3:31am    
Please find below the angular code:-
var es = new EventSource('http://localhost:9080/stream',{withCredentials: true});
es.onmessage = function (event) {
let response=event.data;
response=JSON.parse(response);

that.timeout(function() {that.summary.data.summaryInformation = response.summaryInformation;});
console.log(event.data);
};


Server sent events code:-

@Controller
public class SSEController {

private static final Logger log = Logger.getLogger(SSEController.class);
private final AlertViewService alertViewService;

@Autowired
public SSEController(AlertViewService alertViewService) {
this.alertViewService = alertViewService;
}


@RequestMapping(path = "/stream", method = RequestMethod.GET)
public SseEmitter stream(@AuthenticationPrincipal UserService user) throws IOException {
SummaryView summaryView = alertViewService.summaryInformation();
SseEmitter emitter = new SseEmitter();
ScheduledExecutorService pingThread = Executors.newScheduledThreadPool(1);
emitter.onCompletion(() -> {
log.info("Complete");
pingThread.shutdown();
});
emitter.onTimeout(() -> {
log.info("Timeout");
});
pingThread.scheduleAtFixedRate(() -> {
try {
emitter.send(summaryView, MediaType.APPLICATION_JSON);
} catch (Exception e) {
log.error("Unable to emit", e);
}
} , 100000, 100000, TimeUnit.MILLISECONDS);
return emitter;



}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900