How to get inputs from an authentication failed on spring - authentication

As my project migrated from SPRING 3 to SPRING 5 the methods I had to get the user credentials with AuthenticationException getAuthentication.getPrincipal() became deprecated and now I can't get the info when a user fails to authenticate.
I tried to get the info from the HttpServletRequest with request.getParameter(WebAttributes.AUTHENTICATION_EXCEPTION); but as my authentication object is already null I get null;
I also tried with request.getSession().getAttribute(name); but the code doesn't recognize the "name" variable.

I could get the info needed with request.getparameter("name of your variable"); Here is an exemple;
public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException {
request.getparameter("name");
request.getparameter("lastname");
request.getparameter("id");
}

Related

MobileFirst 8: get client data ( IP address, request data ) in UserAuthenticationSecurityCheck

I'm trying to get some client data inside the UserAuthenticationSecurityCheck.validateCredentials method.
The IP Address is the most important for it.
In the other adapters, I'm using the HttpServletRequest:
#Context
protected HttpServletRequest request;
But this request object is always null in the UserAuthenticationSecurityCheck.
How can I get client data (IP Address or the headers) in this class?
You cannot inject the HttpServletRequest into a security check object(by design - not a bug). Once the user is authenticated, then you can make another Adapter Call, from where you can get the desired details. Unfortunately this is not documented anywhere (not to my knowledge at least).
I had a similar issue with AdapterAPI class as described here.
You can get request in security adapter but not from #Context.
Just override authorize method:
#Override
public void authorize(Set<String> scope, Map<String, Object> credentials, HttpServletRequest request, AuthorizationResponse response) {
//TODO use request object
super.authorize(scope, credentials, request, response);
}

Could Http server return error code before POST body is sent?

If a Http server is not reachable, and Http client is trying to send a POST request to the server, will the Post content ever have the opportunity to be sent or no (say error code come back and the code will not be executed)?
More specifically, I have special logic in writeTo function, I would like to know if it is executed or not if Http server is not reachable.
public interface HttpEntity {
boolean isRepeatable();
boolean isChunked();
long getContentLength();
Header getContentType();
Header getContentEncoding();
InputStream getContent() throws IOException, IllegalStateException;
void writeTo(OutputStream var1) throws IOException;
boolean isStreaming();
void consumeContent() throws IOException;
}

JASPIC Login with Wildfly 9 Send HTTP Return Code

I'm still trying to implement a custom JASPIC login module for Wildfly 9. If the login is successful everything works as expected. But I would expect an HTTP 403 response, if the login is not successful. So I wrote this little test:
#Test
public void invalidCredentials() throws IOException, SAXException {
try {
WebConversation webConversation = new WebConversation();
GetMethodWebRequest request = new GetMethodWebRequest(deployUrl + "LoginServlet");
request.setParameter("token", "invalid");
WebResponse response = webConversation.getResponse(request);
fail("Got " + response.getResponseCode() + " expected 403!");
} catch (final HttpException e) {
assertEquals(403, e.getResponseCode());
}
}
The result is this:
Failed tests:
JaspicLoginTest.invalidCredentials:114 Got 200 expected 403!
I tried this three options to end the method validateRequest of the ServerAuthModule after invalid authentication:
return AuthStatus.SEND_FAILURE;
return AuthStatus.FAILURE;
throw new AuthException();
But none of the above produce a authentication failure HTTP response (403). Is this a Wildfly bug again? Or do I have to produce this return code in an other way?
Ok, obviously one can take the MessageInfo object and can do such like:
public AuthStatus validateRequest(MessageInfo messageInfo,
Subject clientSubject,
Subject serviceSubject) throws AuthException{
//Invalid case:
HttpServletResponse response =
(HttpServletResponse) messageInfo.getResponseMessage();
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return AuthStatus.SEND_FAILURE;
}

How to get past the Authentication Required Spring-boot Security

I have put in the password which is "root" and it keeps popping back up. How can I suppress this or get rid of it. I am using spring boot and spring security.
application.properties
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootpractice
spring.datasource.username=root
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: /
I am using intellij 14 if that matters.
----Update 1-----
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/index")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/index")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
This class has to be in a parent package of all other packages:
WebSecurityConfig.
Also in application.properties set:
security.basic.enabled=false
ACV's answer is probably the easiest way to turn off the authentication completely by adding security.basic.enabled=false to the application.properties file which is usually located under src/main/resources folder.
or you just type in the password :)
1. use default password
When you run your spring application, there is usually a whole bunch of logging printed, which people usually don't read. The password is actually generated and printed to the screen at the startup. and the username is simply user. If you are testing using a browser and it probably only need you enter it once and caches it, so once for all, you should be securely logged in without authenticating every time.
(however, every time you restart your app, it will generate a new password)
2. customize your password
Add the following properties to your application.properties if you want to customize your username and password:
security.user.name=myuser
security.user.password=mypassword
And here is how it looks like with your own username and password
Reference:
Spring Boot Features - Security
Monitoring and Management over HTTP
You can bypass this spring boot security mechanism. See an example below for this:
#SpringBootApplication
#EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
public class SampleSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SampleSpringBootApplication.class, args);
}
}
When Spring Security is in the classpath, Spring Boot by default secures all your pages with Basic authentication. That's why you are being asked for userid and password.
You will need to configure the security. To do so, commonly people would extend a WebSecurityConfigurerAdapter, like this:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
...
Refer this Spring Security guide for more details.
Here was the issues
(1) .loginPage("/index") was saying my login page was at index, however I just wanted to use spring's default login page.
(2) had to to move the security package inside the demo package (the main package). Thanks to #Sanjay for suggesting that. I tried to use #ComponantScan but it could not get it to work.

can not find entity using seam managed persistence context

I'm trying to change the authentication approach in my seam application. I currently use a login form to authenticate. In the future, I'd like to delegate the authentication to another layer that will rewrite every request with a specific HTTP header containing the username of authenticated user.
I'm facing a weird problem: when using login page to authenticate, I'm able to extract the user through the entityManager. But when I query the entityManager using the information off the header, I'm unable to find the user. The entityManager behave like the user does not exist.
I already tried two approaches:
Creating a fake login page which triggers the authentication process
Creating a servlet which gets the request and starts the
authentication process
Both times, the entityManager fails to return me any user.
I read a lot about how seam manages the persistence context, but I didn't find a single explanation which make this issue clear. Do you have any ideas? suggestions? or even guesses?
the code which uses the entityManager is the following:
#Name("userService")
#AutoCreate
public class UserService {
#Logger
private Log logger;
#In
private EntityManager entityManager;
public User getUser(String email) {
try {
return entityManager
.createQuery("SELECT u FROM User u where u.email=:email",
User.class).setParameter("email", email.trim())
.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
The configuration for persistence context is:
<persistence:managed-persistence-context startup="false" scope="stateless"
auto-create="true" name="entityManager" persistence-unit-jndi-name="java:/EntityManagerFactory" />
I created an empty fake login page which executes a page action (authentication) in which i get the request user header as the following:
#Name("applicationAuthenticator")
public class ApplicationAuthenticator {
#Logger
private Log log;
#In
private Identity identity;
#In
private Credentials credentials;
#In(required=true)
private UserService userService;
#Begin
public void login() throws LoginException {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String userName=request.getHeader("user");
identity.unAuthenticate();
credentials.setUsername(userName);
credentials.setPassword("fake");
identity.acceptExternallyAuthenticatedPrincipal(new SimplePrincipal(credentials.getUsername()));
User user=userService.getUserByEmail(credentials.getUsername());
identity.authenticate();
identity.quietLogin();
}
}
Thx in advance :-)
Thx #DaveB for your reply, the code which uses the entityManager is the following:
public User getUser(String email) {
try {
return entityManager
.createQuery("SELECT u FROM User u where u.email=:email",
User.class).setParameter("email", email.trim())
.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
The configuration for persistence context is:
<persistence:managed-persistence-context startup="false" scope="stateless"
auto-create="true" name="entityManager" persistence-unit-jndi-name="java:/EntityManagerFactory" />
I created an empty fake login page which executes a page action (authentication) in which i get the request user header as the following:
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
String userName = request.getHeader("user");