spring restful web service token based authentication

Solutions on MaxInterview for spring restful web service token based authentication by the best coders in the world

showing results for - "spring restful web service token based authentication"
Tyrone
19 Jan 2018
1package es.softtek.jwtDemo.controller;
2
3import java.util.Date;
4import java.util.List;
5import java.util.stream.Collectors;
6
7import org.springframework.security.core.GrantedAuthority;
8import org.springframework.security.core.authority.AuthorityUtils;
9import org.springframework.web.bind.annotation.PostMapping;
10import org.springframework.web.bind.annotation.RequestParam;
11import org.springframework.web.bind.annotation.RestController;
12
13import es.softtek.jwtDemo.dto.User;
14import io.jsonwebtoken.Jwts;
15import io.jsonwebtoken.SignatureAlgorithm;
16
17@RestController
18public class UserController {
19
20	@PostMapping("user")
21	public User login(@RequestParam("user") String username, @RequestParam("password") String pwd) {
22		
23		String token = getJWTToken(username);
24		User user = new User();
25		user.setUser(username);
26		user.setToken(token);		
27		return user;
28		
29	}
30
31	private String getJWTToken(String username) {
32		String secretKey = "mySecretKey";
33		List<GrantedAuthority> grantedAuthorities = AuthorityUtils
34				.commaSeparatedStringToAuthorityList("ROLE_USER");
35		
36		String token = Jwts
37				.builder()
38				.setId("softtekJWT")
39				.setSubject(username)
40				.claim("authorities",
41						grantedAuthorities.stream()
42								.map(GrantedAuthority::getAuthority)
43								.collect(Collectors.toList()))
44				.setIssuedAt(new Date(System.currentTimeMillis()))
45				.setExpiration(new Date(System.currentTimeMillis() + 600000))
46				.signWith(SignatureAlgorithm.HS512,
47						secretKey.getBytes()).compact();
48
49		return "Bearer " + token;
50	}
51}
similar questions