How can we remove the rememberme part from files generated with jhipster ? Do you have some documentation about this part ? I looked into code but it doesn't seem to be done easily, or on wihch template should I see ?
Thanks
Have you tried removing the RememberMe configuration in SecurityConfiguration.java (See commented out code below), and then removed the RememberMe section from login.html? For example:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
// .and()
// .rememberMe()
// .rememberMeServices(rememberMeServices)
// .key(env.getProperty("jhipster.security.rememberme.key"))
.and()
.formLogin() here
Related
I have a login page in spring boot and now I want that page to show only specific links.
Furthermore, my ADMIN User is created during startup, being done with my import.sql
INSERT INTO benutzer(id, created_at, anzeigename, benutzername, dienstnummer, passwort) VALUES (nextval('benutzer_idbenutzer_seq'), now(), 'ADMIN', 'ADMIN', '', 'xxx');
INSERT INTO rolle(id, created_at, bezeichnung) VALUES (nextval('benutzer_idbenutzer_seq'), now(), 'ADMIN');
This is a part of my SecurityConfig class which extends WebSecurityConfigurerAdapter
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
"/",
"/registration**",
"/js/**",
"/css/**",
"/img/**",
"/webjars/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessHandler(customLogoutSuccessHandler)
.permitAll()
.and()
.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
}
And this is my html
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<div sec:authorize="hasRole('ADMIN')">
Should only be shown to ADMIN Users
</div>
Maybe someone knows what I am missing?
Thank you very much!
everything that you wrote sames to be fine, check if there is some missed annotation or if the admin was created at the right way.
here is a small example that works fine on my machine:
#Configuration
public class SecurityConfigurationCompany extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.antMatchers("/profiles").permitAll()
.antMatchers("/dislike").hasAuthority("USER")
.antMatchers("/addParticipant/**").hasAuthority("ADMIN")
.anyRequest().fullyAuthenticated()
.and()
.formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
.and()
.logout().logoutSuccessUrl("/");
}
}
hopefully that was helpful you tell me if it doesnt work
I was able to solve my problem now.
One problem was that my ADMIN user was registered with its username ( username was created in my user table ) but not with its user_role.
After having solved this problem, I had to put the following thing in my html file in order to show specific things:
<div sec:authorize="hasAuthority('ADMIN')">
Shiro web example
I follow this, but in step 2, the stormpath is moved to another site okta, so I don't know what shall I do.
There is an exception:
java.lang.IllegalStateException: Unable to load credentials from any provider in the chain.
So I wrote a reamls by myself.
public class CustomSecurityRealm extends JdbcRealm{
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
char[] psw = upToken.getPassword();
String username = upToken.getUsername();
return new SimpleAuthenticationInfo(username, psw, getName());
}
#Override
public void setDataSource(DataSource dataSource) {
// TODO Auto-generated method stub
DruidDataSource ds=new DruidDataSource();
ds.setUrl("jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE");
ds.setUsername("root");
ds.setPassword("root");
dataSource=ds;
}
}
And in shiro.ini I change securityManager.realm = $stormpathRealm to securityManager.realm = realm.CustomSecurityRealm
But exception is the same. Or sometimes no error when I delete it from tomcat and add again, but home page is not found --404.
I hate this, I just want to see how to use shiro in web project,why it is so hard?
I have no jndi, so I didn't copy from this example, I just want to make things simple. How can I run the web sample?
Take a look at the examples in https://github.com/apache/shiro/tree/master/samples
We will get that tutorial updated too.
I am running an integration test with HttpClient and HttpServer (In-Memory).
When the test runs a token handler (message handler) is executed where I add this code just for a quick test:
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// other code removed for brevity...
var principal1 = CreatePrincipal(1, "test");
Thread.CurrentPrincipal = principal1;
return await base.SendAsync(request, cancellationToken);
}
[Authorize]
[HttpGet]
public HttpResponseMessage Get(int id)
{
return Request.CreateResponse(HttpStatusCode.OK, _service.Get(id));
}
When I debug into the action`s controller constructor I do base.User.Identity.IsAuthenticated and its set to TRUE.
I would have expected that the action is run because the Thread.CurrentPrincipal is set.
Why is it not working?
Thread.CurrentPrincipal is deprecated in Web API v2. Use HttpRequestMessage.GetRequestContext().Principal (both setting and getting)
Whenever you set Thread.CurrentPrincipal, you should set HttpContext.User as well.
Hanselman has a blog post on the subject, and it's also covered in this SO answer. Also note that you may need to force an async yield, as described in this SO answer.
I'm facing a little issue with Spring Security 3.0.x (3.0.2 in particular at the moment). The whole application I'm working on is working perfectly except when someone who doesn't have the authorities tries to log on.
When it occurs, the users is redirected to the "welcome" page, since his username/password are valid, and he receive a cute white page with this : "Error 403: Access is denied"
So, I've been looking on the net trying to find how this behavior can be handled. So far I've come to the conclusion, please correct me if I'm wrong, that it is managed by the ExceptionTranslationFilter. But I don't quite understand how to make any good use of this information.
I've tryied to edit my SecurityContext.xml to add a access-denied-handler tag to my http tag, but it doesn't work. Do I need to add more than this tag to make it work? Is there any other possibilities to make my application more user-friendly?
Edit : I would like to redirect to a page, let's says 403.html, for example.
Sincerly,
Thanks
I still don't get why you had to implement your own access handler... I have currently faced same task:
<security:access-denied-handler error-page="/accessDenied"/> - works like charm.
Don't forget to specify handler in your Controller:
#RequestMapping(value = "/accessDenied")
public String accessDenied() {
return "accessDenied"; // logical view name
}
Update for Spring Boot(2014 Oct):
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedHandler(customHandler) OR .accessDeniedPage("/somePage.html").and
.formLogin()
.failureHandler(ajaxAuthenticationFailureHandler)}
Nowadays we don't really return views for such task since angular js kicks in so you can use your failure/success handler and return tailored JSON responses. For us it was sufficient to use failure handler but you get to choose where you want your control to kick in. We generally don't use view resolvers as there are UI tiles frameworks(such as angular partials) able to construct pieces into single page for you. Html pieces are stored on the server and served simply as static resources.
Lets play with Embedded Tomcat to achieve similar behavior to web.xml !
#Configuration
#EnableAutoConfiguration
public class ApplicationWebXml extends SpringBootServletInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.profiles(addDefaultProfile())
.showBanner(false)
.sources(Application.class);
}
//required for container customizer to work, the numerous tutorials didn't work for me, so I simply tried overriding the default one
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
return tomcat;
}
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer(
) {
return new EmbeddedServletContainerCustomizer() {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
containerFactory.setSessionTimeout(1); // just for your interest, remove as necessary
containerFactory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN,"/views/accessDenied.html"),
new ErrorPage(HttpStatus.NOT_FOUND,"/views/notFound.html"));
containerFactory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
#Override
public void customize(Connector connector) {
connector.setPort(8082);// just for your interest, remove as necessary
}
});
}
};
}
}
A cleaner way to handle error redirects is to use the <error-page> and <error-code> tags in your web.xml. See below for an example:
<!-- Custom 403 Error Page -->
<!--
NOTE: Security will throw this error when a user has been authenticated successfully
but lacks the permissions to perform the requested action.
-->
<error-page>
<error-code>403</error-code>
<location>/403.jsp</location>
</error-page>
This block of code will redirect to the specified location whenever it encounters the specified error code.
This eliminates the need for authorization code inside your application logic.
I've found how to do this. By implementing the AccessDeniedHandler interface and the corresponding handle method I can, easily, control the way the Http 403 error is handled.
This way, you can add various items in the session and then intercept them on your jsp.
The xml file then looks like this :
<sec:http>
<!-- lots of urls here -->
<sec:access-denied-handler ref="accessDeniedHandler" />
<sec:anonymous/>
</sec:http>
<bean id="accessDeniedHandler" class="foo.bar.CustomAccessDeniedHandler">
<property name="accessDeniedUrl" value="403.html" />
</bean>
The java class :
package foo.bar;
public class CustomAccessDeniedHandler implements org.springframework.security.web.access.AccessDeniedHandler {
private String accessDeniedUrl;
public CustomAccessDeniedHandler() {
}
public CustomAccessDeniedHandler(String accessDeniedUrl) {
this.accessDeniedUrl = accessDeniedUrl;
}
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendRedirect(accessDeniedUrl);
request.getSession().setAttribute("CustomSessionAttribute", "value here");
}
public String getAccessDeniedUrl() {
return accessDeniedUrl;
}
public void setAccessDeniedUrl(String accessDeniedUrl) {
this.accessDeniedUrl = accessDeniedUrl;
}
}
And a jsp example :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:if test="${!empty CustomSessionAttribute}">
<br/>
ACCESS IS DENIED
<br/>
</c:if>
<!-- other stuff down here -->
The way to make this work is to define a handler in your entry point:
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException, ServletException {
if (authException != null) {
// you can check for the spefic exception here and redirect like this
response.sendRedirect("403.html");
}
}
}
You can define this as your entry point by setting this as you entry point in the xml config file:
<http entry-point-ref="customAuthenticationEntryPoint">
...
</http>
You have checked the tag in an application and to me it seems to work.
<sec:access-denied-handler error-page="/handle403Url" />
where handle403Url I want to call to handle this error (for example to show an error).
Don't forget that you have to allow this url in the filters so it can be reached by this user authority, so in the start of the flters you have to add something like this:
<sec:intercept-url pattern="/handle403Url" filters="none" />
I am using wicket 1.4.7 + spring 3.0 + spring security 3.0
Problem is : Spring security authenticate the user via cookie (remember-me service) but Wicket's AuthenticatedWebSession couldn't understand this and populate login panel. How can i solve it ?
Thanks.
Pretty old question, but I just stumbled upon it while research the exact same problem. So if anybody else comes across this, here's my solution.
The problem is that AuthenticatedWebSession#isSignedIn() ignores the SecurityContext and checks it's own boolean flag instead. As it isn't possible to override the final method #isSignedIn(), there has to be a workaround. I've gone for a custom WebRequestCycle overriding #onBeginRequest() to synchronize state just before Wicket starts processing the current request:
// MyApplication.java
public MyApplication extends AuthenticatedWebApplication {
// SNIP
#Override
public RequestCycle newRequestCycle(final Request request, final Response response) {
return new WebRequestCycle(this, (WebRequest) request, (WebResponse) response) {
#Override
protected void onBeginRequest() {
MySession.get().updateSignIn();
}
};
}
}
// MySession.java
public class MySession extends AuthenticatedWebSession {
// SNIP
void updateSignIn() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
signIn(auth != null && auth.isAuthenticated());
}
}
Alternatively, AuthenticatedWebSession and AuthenticatedWebApplication could be abandoned alltogether as the rest of wicket-auth-roles doesn't require them. It just takes some code duplication from AuthenticatedWebApplication to make everything work similarly.