Feign AuthRequest - java

In my first developmentstep i logged in with my FeignClient.
That works well.
public class FeignClientConfiguration {
public String userkrz = "abc";
public String password = "123xy456";
#Bean // ({"authBean"})
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor( userkrz, password );
}
}
public class FeignClientConfiguration {
public String userkrz = "abc";
public String password = "123xy456";
#Bean // ({"authBean"})
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor( userkrz, password );
}
}
But the client authorized by starting the client and I dont know how I authorized me later.
I would set the credentials concerning the runtime.

Related

Spring Vault client - not able to connect to local dev Vault server

I installed Vault locally. I was able to start local dev server and write/read some secrets into Vault kv based on this official tutorial https://learn.hashicorp.com/vault/
Then I wanted to create some very basic Java/Spring Boot demo client that would connect to my local Vault dev server in order to write/read secrets. I read Baeldung tutorial for inspiration https://www.baeldung.com/spring-vault.
This is my vault-config.properties:
vault.uri=http://127.0.0.1:8200
vault.token=s.EXg6MQwUuB63Z7Xra4zybOut (token generated after the latest start of server)
Then service class:
#Service
public class CredentialsService {
#Autowired
private VaultTemplate vaultTemplate;
public void secureCredentials(Credentials credentials) throws URISyntaxException {
vaultTemplate.write("credentials/myapp", credentials);
}
public Credentials accessCredentials() throws URISyntaxException {
VaultResponseSupport<Credentials> response = vaultTemplate.read("credentials/myapp", Credentials.class);
return response.getData();
}
}
Configuration class:
#Configuration
public class VaultConfig extends AbstractVaultConfiguration {
#Override
public ClientAuthentication clientAuthentication() {
return new TokenAuthentication("s.EXg6MQwUuB63Z7Xra4zybOut");
}
#Override
public VaultEndpoint vaultEndpoint() {
return VaultEndpoint.create("host", 8200);
}
}
and this:
#Configuration
#PropertySource(value = { "vault-config.properties" })
#Import(value = EnvironmentVaultConfiguration.class)
public class VaultEnvironmentConfig {
}
One domain object:
public class Credentials {
private String username;
private String password;
public Credentials() {
}
public Credentials(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public String toString() {
return "Credential [username=" + username + ", password=" + password + "]";
}
}
And finally my main Spring Boot class:
#RestController
#ComponentScan
#SpringBootApplication
public class SpringVaultTutorial {
#Autowired
CredentialsService credentialsService;
#RequestMapping("/")
String home() throws URISyntaxException {
Credentials credentials = new Credentials("oliver","exxeta123");
credentialsService.secureCredentials(credentials);
return credentialsService.accessCredentials().getUsername().toString();
}
public static void main(String[] args) {
SpringApplication.run(SpringVaultTutorial.class, args);
}
}
Main class should write secret and then immediately read it and print username. But I am getting this error message:
There was an unexpected error (type=Internal Server Error, status=500).
I/O error on POST request for "https://host:8200/v1/credentials/myapp": host; nested exception is java.net.UnknownHostException: host
Does somebody have a clue what can be wrong?
EDIT:
Based on advice from Arun I followed this tutorial https://drissamri.be/blog/java/enable-https-in-spring-boot/
I have been trying both approaches.
1) Modify application.properties:
server.port: 8443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: oliver
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
security.require-ssl=true
After modification, when I call https://localhost:8443, I am getting Exception:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:710) ~[na:1.8.0_121]
at sun.security.ssl.InputRecord.read(InputRecord.java:527) ~[na:1.8.0_121]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973) ~[na:1.8.0_121]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375) ~[na:1.8.0_121]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403) ~[na:1.8.0_121]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387) ~[na:1.8.0_121]
2) Second approach based on tutorial is about adding ConnectorConfig class:
#Configuration
public class ConnectorConfig {
#Bean
public ServletWebServerFactory servletContainer() {
TomcatServletWebServerFactory tomcat =
new TomcatServletWebServerFactory() {
#Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
tomcat.addAdditionalTomcatConnectors(redirectConnector());
return tomcat;
}
private Connector redirectConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8090);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
But after calling localhost:8090 that redirects me to https://localhost:8443, I am getting the same error: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(InputRecord.java:710) ~
Now the question is: Do I have to configure something also on the Vault side regarding certificate? Or do you think there could be some certificate problem on Java client side? But I thing if there was Java certificate problem, exception would be thrown already during startup.
Problem solved. Now I am able to connect to local Vault from Java client. I paste code here if someone in the future wants to run simple Java Client - Vault demo.
Controller:
#RestController
#RequestMapping(Paths.ROOT)
#Api(value = Paths.ROOT, description = "Endpoint for core testing")
public class Controller {
#Autowired
CredentialsService credentialsService;
#GetMapping("/")
String home() throws URISyntaxException {
Credentials credentials = new Credentials("oliver", "exxeta123");
credentialsService.secureCredentials(credentials);
return credentialsService.accessCredentials().toString();
}
#GetMapping("/test")
public String test() throws IOException {
// http://127.0.0.1:8200/v1/sys/internal/ui/mounts/secret/mysecrets
VaultConfig vc = new VaultConfig();
String bearerToken = vc.clientAuthentication().login().getToken();
System.out.println(bearerToken);
// credentialsService.accessCredentials()
// Sending get request
//URL url = new URL("http://127.0.0.1:8200/v1/sys/internal/ui/mounts/secret/mysecrets");
// URL updated to match readme.adoc
URL url = new URL("http://127.0.0.1:8200/v1/kv/my-secret");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + bearerToken);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
// printing result from response
return "Response: - " + response.toString();
}
#GetMapping(value = { "/add/{name}/{username}/{password}" })
public ResponseEntity<String> addKey(#PathVariable(value = "name", required = false, name = "name") String name,
#PathVariable(value = "username", required = false, name = "username") String username,
#PathVariable(value = "password", required = false, name = "password") String password) throws URISyntaxException {
Credentials credentials = new Credentials(username, password);
credentialsService.secureCredentials(name, credentials);
return new ResponseEntity<>("Add success: " + credentialsService.accessCredentials(name).getUsername(), HttpStatus.OK);
}
#GetMapping(value = {"/get", "/get/{name}"})
public ResponseEntity<Credentials> getKey(#PathVariable(value = "name", required = false, name = "name") String name) {
return new ResponseEntity<>(credentialsService.accessCredentials(name), HttpStatus.OK);
}
#GetMapping(value= {"/delete", "/delete/{name}"})
public String removeKey(#PathVariable(value = "name", required = false, name = "name") String name) {
return "Delete success: " + credentialsService.deleteCredentials(name);
}
}
Service:
#Service
public class CredentialsService {
private VaultTemplate vaultTemplate;
/**
* To Secure Credentials
*
* #param credentials
* #return VaultResponse
* #throws URISyntaxException
*/
public void secureCredentials(Credentials credentials) throws URISyntaxException {
//vaultTemplate.write("credentials/myapp", credentials);
initVaultTemplate();
vaultTemplate.write("kv/myapp", credentials);
}
public void secureCredentials(String storagePlace, Credentials credentials) {
initVaultTemplate();
vaultTemplate.write("kv/" + storagePlace, credentials);
}
/**
* To Retrieve Credentials
*
* #return Credentials
* #throws URISyntaxException
*/
public Credentials accessCredentials() throws URISyntaxException {
//VaultResponseSupport<Credentials> response = vaultTemplate.read("credentials/myapp", Credentials.class);
initVaultTemplate();
VaultResponseSupport<Credentials> response = vaultTemplate.read("kv/myapp", Credentials.class);
return response.getData();
// TODO special case when there are no values
}
/**
* #param nameOfsecrets key name
* #return if is presented or empty object
*/
public Credentials accessCredentials(String nameOfsecrets) {
initVaultTemplate();
VaultResponseSupport<Credentials> response = vaultTemplate.read("kv/" + nameOfsecrets, Credentials.class);
if (response != null) {
return response.getData();
} else {
return new Credentials();
}
}
public boolean deleteCredentials(String name) {
initVaultTemplate();
vaultTemplate.delete("kv/" + name);
return true;
}
}
private void initVaultTemplate() {
VaultEndpoint endpoint = new VaultEndpoint();
endpoint.setHost("localhost");
endpoint.setPort(8200);
endpoint.setScheme("http");
vaultTemplate = new VaultTemplate(endpoint, new VaultConfig().clientAuthentication());
}
VaultConfig:
#Configuration
public class VaultConfig extends AbstractVaultConfiguration {
#Override
public ClientAuthentication clientAuthentication() {
return new TokenAuthentication("00000000-0000-0000-0000-000000000000");
}
#Override
public VaultEndpoint vaultEndpoint() {
return VaultEndpoint.create("localhost", 8200);
}
}
VaultEnvironmentConfig:
#Configuration
#PropertySource(value = { "vault-config.properties" })
#Import(value = EnvironmentVaultConfiguration.class)
public class VaultEnvironmentConfig {
}
Main class:
#SpringBootApplication
#EnableSwagger2
public class SpringVaultTutorial {
public static void main(String[] args) {
SpringApplication.run(SpringVaultTutorial.class, args);
}
//SWAGGER DOCUMENTATION BEANS
// default group contains all endpoints
#Bean
public Docket defaultApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())//all
.build().apiInfo(apiInfo());
}
// Management group contains Spring Actuator endpoints
#Bean
public Docket swaggerAdminEndpoints() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName(Paths.ROOT)
.apiInfo(apiInfo())
.select()
.paths(PathSelectors.regex("/v1/.*"))
.build()
.forCodeGeneration(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Vault Demo Application")
.description("Demo Application using vault")
.version("1.0")
.build();
}
}
vault-config.properties:
vault.uri=http://127.0.0.1:8200
vault.token=00000000-0000-0000-0000-000000000000
application.properties:
server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS
Paths:
public class Paths {
public static final String ROOT = "/v1";
}
Credentials:
public class Credentials {
private String username;
private String password;
public Credentials() {
}
public Credentials(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
#Override
public String toString() {
return "Credential [username=" + username + ", password=" + password + "]";
}
}
UnknownHostException is due to no server is available with the name 'host'. you can either add an entry in hosts file map to localhost. or try changing the host name while creating vault as
#Override
public VaultEndpoint vaultEndpoint() {
return VaultEndpoint.create("localhost", 8200);
}

How do you use Spring Retry with Spring Vault Configuration with VaultPropertySource?

I want spring-vault configuration marked with VaultPropertySource to be able to retry the requests to the vault if they fail.
What should i mark as retryable ? I'm using Spring-Retry and i was looking over http://www.baeldung.com/spring-retry .
There is no visible method to mark as retryable. Should I change the implementation of the vaultTemplate and mark the vaultOperations as retryable ?
ProvisioningSecrets.java
#Configuration
#VaultPropertySource(
value="secret/provisioning",
propertyNamePrefix = "provisioning.",
renewal = Renewal.RENEW
)
#EnableRetry
#Lazy
#Profile("!test")
public class ProvisioningSecrets {
private static final Logger logger = LoggerFactory.getLogger(ProvisioningSecrets.class);
#Autowired
public void setPassword(#Value("${provisioning.password}") final String password) throws Exception {
logger.info("We successfully set the provisioning db password.");
EnvVars.changeSetting(Setting.PROVISIONING_PASS, password);
}
#Autowired
public void setHost(#Value("${provisioning.host}") final String host) throws Exception {
logger.info("We successfully set the provisioning db host.");
EnvVars.changeSetting(Setting.PROVISIONING_HOST, host);
}
#Autowired
public void setPort(#Value("${provisioning.port}") final int port) throws Exception {
logger.info("We successfully set the provisioning db port.");
EnvVars.changeSetting(Setting.PROVISIONING_PORT, Integer.toString(port));
}
#Autowired
public void setUsername(#Value("${provisioning.username}") final String username) throws Exception {
logger.info("We successfully set the provisioning db username.");
EnvVars.changeSetting(Setting.PROVISIONING_USER, username);
}
#Autowired
public void setDbName(#Value("${provisioning.name}") final String name) throws Exception {
logger.info("We successfully set the provisioning db name.");
EnvVars.changeSetting(Setting.PROVISIONING_DB_NAME, name);
}
}
VaultConfiguration.java
#Configuration
#Profile("!test")
public class VaultConfiguration extends AbstractVaultConfiguration {
private static final Logger logger = LoggerFactory.getLogger(VaultConfiguration.class);
private URI vaultHost;
private String vaultToken;
/**
* Configure the Client Authentication.
*
* #return A configured ClientAuthentication Object.
* #see ClientAuthentication
*/
#Override
public ClientAuthentication clientAuthentication() {
// testing out environment variable value injection
logger.debug("Vault Token configuration done.");
return new TokenAuthentication(vaultToken);
}
#Override
#Bean
#DependsOn("vaultToken")
public SessionManager sessionManager() {
return super.sessionManager();
}
#Override
public SslConfiguration sslConfiguration() {
logger.info("Configuring Vault SSL with NONE.");
return SslConfiguration.NONE;
}
/**
* Specify an endpoint for connecting to Vault.
*
* #return A configured VaultEndpoint.
* #see VaultEndpoint
*/
#Override
public VaultEndpoint vaultEndpoint() {
logger.debug("Vault Host:" + vaultHost.toString());
if (vaultHost.toString().isEmpty()) {
logger.info("Creating default Vault Endpoint.");
return new VaultEndpoint();
}
logger.info("Creating Vault Endpoint based on address: " + vaultHost.toString());
final VaultEndpoint endpoint = VaultEndpoint.from(vaultHost);
logger.info("Created Vault Endpoint: " + endpoint.toString());
return endpoint;
}
#Bean("vaultHost")
public URI vaultHost(#Value("${spring.vault.host}") final URI vaultHost) {
this.vaultHost = vaultHost;
return vaultHost;
}
#Override
#Bean
#DependsOn("vaultHost")
public VaultTemplate vaultTemplate() {
return super.vaultTemplate();
}
#Bean("vaultToken")
public String vaultToken(#Value("${spring.vault.token}") final String vaultToken) {
this.vaultToken = vaultToken;
return vaultToken;
}
}
How about creating a custom VaultTemplate bean class using RetryTemplate?
public class RetryableVaultTemplate extends VaultTemplate {
private final RetryTemplate retryTemplate;
public RetryableVaultTemplate(VaultEndpointProvider endpointProvider,
ClientHttpRequestFactory clientHttpRequestFactory,
SessionManager sessionManager, RetryTemplate retryTemplate) {
super(endpointProvider, clientHttpRequestFactory, sessionManager);
this.retryTemplate = retryTemplate;
}
#Override
public VaultResponse read(final String path) {
return retryTemplate
.execute(new RetryCallback<VaultResponse, RuntimeException>() {
#Override
public VaultResponse doWithRetry(RetryContext context) {
System.out.println("doWithRetry");
return RetryableVaultTemplate.super.read(path);
}
});
}
#Override
public <T> VaultResponseSupport<T> read(final String path, final Class<T> responseType) {
return retryTemplate
.execute(new RetryCallback<VaultResponseSupport<T>, RuntimeException>() {
#Override
public VaultResponseSupport<T> doWithRetry(RetryContext context) {
return RetryableVaultTemplate.super.read(path, responseType);
}
});
}
}
Make sure to register this bean class as vaultTemplate bean instead of VaultTemplate.

Creating JSON Web Tokens through Basic Authentication endpoint? Dropwizard

Using Dropwizard 1.2.0 and Dropwizard JWT library, I am trying to create json web tokens from an API endpoint called /token
This endpoint requires the client to pass a username and password, using Basic Authentication method. If successful the response will contain a JSON web token.
Principal
public class ShepherdAuth implements JwtCookiePrincipal {
private String name;
private Set<String> roles;
public ShepherdAuth(String name, Set<String> roles) {
this.name = checkNotNull(name, "User name is required");
this.roles = checkNotNull(roles, "Roles are required");
}
#Override
public boolean isPersistent() {
return false;
}
#Override
public boolean isInRole(final String s) {
return false;
}
#Override
public String getName() {
return this.name;
}
#Override
public boolean implies(Subject subject) {
return false;
}
public Set<String> getRoles() {
return roles;
}
}
Authenticator
public class ShepherdAuthenticator implements Authenticator<BasicCredentials, ShepherdAuth> {
private static final Map<String, Set<String>> VALID_USERS = ImmutableMap.of(
"guest", ImmutableSet.of(),
"shepherd", ImmutableSet.of("SHEPHERD"),
"admin", ImmutableSet.of("ADMIN", "SHEPHERD")
);
#Override
public Optional<ShepherdAuth> authenticate(BasicCredentials credentials) throws AuthenticationException {
if (VALID_USERS.containsKey(credentials.getUsername()) && "password".equals(credentials.getPassword())) {
return Optional.of(new ShepherdAuth(credentials.getUsername(), VALID_USERS.get(credentials.getUsername())));
}
return Optional.empty();
}
}
Resource / Controller
public class ShepherdController implements ShepherdApi {
public ShepherdController() {
}
#PermitAll
#GET
#Path("/token")
public ShepherdAuth auth(#Auth final BasicCredentials user) {
return new ShepherdAuth(user.getUsername(),
ImmutableSet.of("SHEPHERD"));
}
App / Config
#Override
public void run(final ShepherdServiceConfiguration configuration,
final Environment environment) {
final ShepherdController shepherdController = new ShepherdController();
// app authentication
environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<ShepherdAuth>()
.setAuthenticator(new ShepherdAuthenticator())
.setAuthorizer(new ShepherdAuthorizer())
.setRealm(configuration.getName())
.buildAuthFilter()));
When I try to make a request to /shepherd/token I do not get a prompt for basic auth, instead I get a HTTP 401 response with
Credentials are required to access this resource.
How do I get the controller to prompt for username and password and generate a JWT on success?
I implemented JWT tokens in my project by using https://github.com/jwtk/jjwt but the solution will easily be applied to another library. The trick is to use different authenticators.
This answer is not suited for Dropwizard JWT Library but does the fine job of providing JWT for Dropwizard :)
First, the application:
environment.jersey().register(new TokenResource(configuration.getJwsSecretKey()));
environment.jersey().register(new HelloResource());
environment.jersey().register(RolesAllowedDynamicFeature.class);
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
environment.jersey()
.register(
new AuthDynamicFeature(
new ChainedAuthFilter<>(
Arrays
.asList(
new JWTCredentialAuthFilter.Builder<User>()
.setAuthenticator(
new JWTAuthenticator(configuration.getJwsSecretKey()))
.setPrefix("Bearer").setAuthorizer(new UserAuthorizer())
.buildAuthFilter(),
new JWTDefaultCredentialAuthFilter.Builder<User>()
.setAuthenticator(new JWTDefaultAuthenticator())
.setAuthorizer(new UserAuthorizer()).setRealm("SUPER SECRET STUFF")
.buildAuthFilter()))));
Please note that the configuration class must contain a configuration setting:
String jwsSecretKey;
Here, the TokenResource is the token supplying resource, and the HelloResource is our test resource. User is the principal, like this:
public class User implements Principal {
private String name;
private String password;
...
}
And there is one class for communicating the JWT token:
public class JWTCredentials {
private String jwtToken;
...
}
TokenResource provides tokens for a user "test" with password "test":
#POST
#Path("{user}")
#PermitAll
public String createToken(#PathParam("user") String user, String password) {
if ("test".equals(user) && "test".equals(password)) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(this.secretKey);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
JwtBuilder builder = Jwts.builder().setIssuedAt(now).setSubject("test")
.signWith(signatureAlgorithm, signingKey);
return builder.compact();
}
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
And the HelloResource just echoes back the user:
#GET
#RolesAllowed({"ANY"})
public String hello(#Auth User user) {
return "hello user \"" + user.getName() + "\"";
}
JWTCredentialAuthFilter provides credentials for both authentication schemes:
#Priority(Priorities.AUTHENTICATION)
public class JWTCredentialAuthFilter<P extends Principal> extends AuthFilter<JWTCredentials, P> {
public static class Builder<P extends Principal>
extends AuthFilterBuilder<JWTCredentials, P, JWTCredentialAuthFilter<P>> {
#Override
protected JWTCredentialAuthFilter<P> newInstance() {
return new JWTCredentialAuthFilter<>();
}
}
#Override
public void filter(ContainerRequestContext requestContext) throws IOException {
final JWTCredentials credentials =
getCredentials(requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION));
if (!authenticate(requestContext, credentials, "JWT")) {
throw new WebApplicationException(
this.unauthorizedHandler.buildResponse(this.prefix, this.realm));
}
}
private static JWTCredentials getCredentials(String authLine) {
if (authLine != null && authLine.startsWith("Bearer ")) {
JWTCredentials result = new JWTCredentials();
result.setJwtToken(authLine.substring(7));
return result;
}
return null;
}
}
JWTAuthenticator is when JWT credentials are provided:
public class JWTAuthenticator implements Authenticator<JWTCredentials, User> {
private String secret;
public JWTAuthenticator(String jwtsecret) {
this.secret = jwtsecret;
}
#Override
public Optional<User> authenticate(JWTCredentials credentials) throws AuthenticationException {
try {
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(this.secret))
.parseClaimsJws(credentials.getJwtToken()).getBody();
User user = new User();
user.setName(claims.getSubject());
return Optional.ofNullable(user);
} catch (#SuppressWarnings("unused") ExpiredJwtException | UnsupportedJwtException
| MalformedJwtException | SignatureException | IllegalArgumentException e) {
return Optional.empty();
}
}
}
JWTDefaultAuthenticator is when no credentials are present, giving the code an empty user:
public class JWTDefaultAuthenticator implements Authenticator<JWTCredentials, User> {
#Override
public Optional<User> authenticate(JWTCredentials credentials) throws AuthenticationException {
return Optional.of(new User());
}
}
UserAuthorizer permits the "ANY" role, as long as the user is not null:
public class UserAuthorizer implements Authorizer<User> {
#Override
public boolean authorize(User user, String role) {
return user != null && "ANY".equals(role)
}
}
If all goes well,
curl -s -X POST -d 'test' http://localhost:8080/token/test
will give you something like:
eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MDk3MDYwMjYsInN1YiI6InRlc3QifQ.ZrRmWTUDpaA6JlU4ysIcFllxtqvUS2OPbCMJgyou_tY
and this query
curl -s -X POST -d 'xtest' http://localhost:8080/token/test
will fail with
{"code":401,"message":"HTTP 401 Unauthorized"}
(BTW, "test" in the URL is the user name and "test" in the post data is the password. As easy as basic auth, and can be configured for CORS.)
and the request
curl -s -X GET -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MDk3MDYwMjYsInN1YiI6InRlc3QifQ.ZrRmWTUDpaA6JlU4ysIcFllxtqvUS2OPbCMJgyou_tY' http://localhost:8080/hello
will show
hello user "test"
while
curl -s -X GET -H 'Authorization: Bearer invalid' http://localhost:8080/hello
and
curl -s -X GET http://localhost:8080/hello
will result in
{"code":403,"message":"User not authorized."}
Your missing this line in your configuration.
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));

Spring MVC Web Request and Android Request to Same Method

I have an spring mvc web application in which users login to session "session.setAttribute" classically. Whenever I need loggedin user data I use this data.
Now I want to add android app and what I want to learn do I have to add additional methods for each android request and send user data within it?
Or Is there away to make a request to same methods.
What is the consept for this kind of cloud apps? Do I have to write different methods for android requests? Because it is not possible session.getAttribute when wemake an android request, it returns null.
User user = userService.getByUserNameAndPassword(userName, password);
if (user != null) {
if (user.isActive()) {
Account account = new Account(user, request.getRemoteAddr());
HttpSession httpSession = request.getSession(true);
AccountRegistry.add(httpSession);
httpSession.setAttribute(Constant.ACCOUNT, account);
result.put(Constant.REF, Constant.SUCCESS);
}
public class Account {
private UserRightsHandler userRightsService = null;
private User user;
private String ipAddress;
private boolean admin;
public Account(User user, String ipAddress) {
this.user = user;
this.ipAddress = ipAddress;
userRightsService = new UserRightsHandler(user);
setAdmin(userRightsService.isAdmin());
}
public UserRightsHandler getUserRightsService() {
return userRightsService;
}
public User getUser() {
return this.user;
}
public String getIpAddress() {
return ipAddress;
}
public boolean isAdmin() {
return admin;
}
private void setAdmin(boolean admin) {
this.admin = admin;
}
}
public class AccountRegistry {
private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();
public static void add(HttpSession session) {
sessions.put(session.getId(), session);
}
public static void remove(HttpSession session) {
if (session != null) {
sessions.remove(session.getId());
session.setAttribute(Constant.ACCOUNT, null);
session.invalidate();
}
}
public static HttpSession getByHttpSessionID(String httpSessionID) {
Set<String> keys = sessions.keySet();
Iterator it = keys.iterator();
while (it.hasNext()) {
String sID = (String) it.next();
HttpSession session = sessions.get(sID);
if (sID.equals(httpSessionID)) {
return session;
}
}
return null;
}
public static void removeByHttpSessionID(String httpSessionID) {
HttpSession session = getByHttpSessionID(httpSessionID);
remove(session);
}
public static Account getCurrentAccount() {
HttpServletRequest request = ContextFilter.getCurrentInstance().getRequest();
HttpSession session = request.getSession();
return (Account) session.getAttribute(Constant.ACCOUNT);
}
}
#RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
public #ResponseBody
String changeStatus(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
User editor = AccountRegistry.getCurrentAccount().getUser();
}
You can ask user send their user and password at the start of Android app via custom authenticate request like /appLogin then if it is correct creditentals you can return a key to user (to app) and store it to some variable during app run. Then when user want to do something send a request to server you can send it to a function with mapping like /appExampleService then you can check at that function this key and device valid depending on how you handle custom login process then this function call existing function that is used for web browsers that have mapping /exampleService. For example;
#JsonSerialize
#RequestMapping("/appExampleService")
public int someServiceForAppClient(
#RequestParam(value = "key", required = true) String apikey,
#RequestParam(value = "param", required = true) String someParam{
String name=userDAO.getUsernameFromApiKey(apikey);
return someService(someParam, name);
}
#JsonSerialize
#RequestMapping("/exampleService")
public int someServiceForWebClient(
#RequestParam(value = "param", required = true) String someParam) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
return someService(someParam, name);
}
public int someService(String someParam,String name){
return doBusiness(someParam, name);
}
userDAO is just something I created for to get info of user with given key. And there is a service for App login as well which return that key to user when he started the app send his username and pass

Spring social siginIn() not firing on successful authentication

I've implemented Spring Social and have successfully been able to implement the ProviderSignInController to authenticate connections to Facebook.
As part of this I needed to implement the SignInAdapter interface. I understand this interface is used in the final steps of a successful authentication with a provider, specifically I'm overriding the signIn method to log the client into my application programmatically after successful authentication with the provider.
My problem is that when I implement the SignInAdapter it doesn't fire the signIn() method on successful login.
The code is almost straight out of the Spring showcase examples:
public class SimpleSignInAdapter implements SignInAdapter {
private static final Logger logger = LoggerFactory.getLogger(SimpleSignInAdapter.class);
private final RequestCache requestCache;
#Inject
public SimpleSignInAdapter(RequestCache requestCache) {
this.requestCache = requestCache;
logger.debug("Constructing " + SimpleSignInAdapter.class.getCanonicalName());
}
#Override
public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
/* A social profile has been found. Now we need to log that user into the
* application programatically.
*
* No other credentials are necessary here because by the time this method
* is called the user will have signed into the provider and their connection
* with that provider has been used to prove the user's identity.
*/
logger.debug("A social profile has been found. Now we need to log that user into the app.");
SignInUtils.signin(localUserId);
return null;
}
private String extractOriginalUrl(NativeWebRequest request) {
HttpServletRequest nativeReq = request.getNativeRequest(HttpServletRequest.class);
HttpServletResponse nativeRes = request.getNativeResponse(HttpServletResponse.class);
SavedRequest saved = requestCache.getRequest(nativeReq, nativeRes);
if (saved == null) {
return null;
}
requestCache.removeRequest(nativeReq, nativeRes);
removeAutheticationAttributes(nativeReq.getSession(false));
return saved.getRedirectUrl();
}
private void removeAutheticationAttributes(HttpSession session) {
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
}
The interesting this is that the SimpleSignInAdapter is constructed as I can debug through that step and see my debug output in the log so it seems the Bean is being instantiated just not firing the signIn method.
Here's my Spring configuration:
#Configuration
#ComponentScan(basePackages = "com.mycompany.webclient")
#PropertySource("classpath:app.properties")
#ImportResource("/WEB-INF/spring/appServlet/security-app-context.xml")
public class MainConfig {
#Bean
public PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
And my Spring Social config is:
#Configuration
#EnableSocial
public class SocialConfig implements SocialConfigurer {
private SocialUserDAO socialUserDao;
//
// SocialConfigurer implementation methods
//
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
cfConfig.addConnectionFactory(new FacebookConnectionFactory("XXXXXXXXX", "XXXXXXXXX"));
cfConfig.addConnectionFactory(new TwitterConnectionFactory("XXXXXXXXX", "XXXXXXXXX"));
}
#Override
public UserIdSource getUserIdSource() {
return new UserIdSource() {
#Override
public String getUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return authentication.getName();
}
};
}
#Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new HibernateUsersConnectionRepository(socialUserDao, connectionFactoryLocator, Encryptors.noOpText());
}
//
// API Binding Beans
//
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public Facebook facebook(ConnectionRepository repository) {
Connection<Facebook> connection = repository.findPrimaryConnection(Facebook.class);
return connection != null ? connection.getApi() : null;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public Twitter twitter(ConnectionRepository repository) {
Connection<Twitter> connection = repository.findPrimaryConnection(Twitter.class);
return connection != null ? connection.getApi() : null;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public LinkedIn linkedin(ConnectionRepository repository) {
Connection<LinkedIn> connection = repository.findPrimaryConnection(LinkedIn.class);
return connection != null ? connection.getApi() : null;
}
//
// Web Controller and Filter Beans
//
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
connectController.addInterceptor(new PostToWallAfterConnectInterceptor());
connectController.addInterceptor(new TweetAfterConnectInterceptor());
return connectController;
}
#Bean
public ProviderSignInController providerSignInController(ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SimpleSignInAdapter(new HttpSessionRequestCache()));
}
#Bean
public DisconnectController disconnectController(UsersConnectionRepository usersConnectionRepository, Environment env) {
return new DisconnectController(usersConnectionRepository, env.getProperty("facebook.clientSecret"));
}
#Bean
public ReconnectFilter apiExceptionHandler(UsersConnectionRepository usersConnectionRepository, UserIdSource userIdSource) {
return new ReconnectFilter(usersConnectionRepository, userIdSource);
}
}
Is there any way for me to confirm why the signIn() is not being fired or even if it is being registered.

Categories