Why sec:authentication="name" show all user information? - spring

I use Spring Boot, Spring Boot Security, thymeleaf-extras-springsecurity5. I want get information about current user and write:
<div sec:authorize="isAuthenticated()">
Authenticated as <span sec:authentication="name"></span></div>
and get All User information Like that:
Authenticated as User(id=7, firstName=TOGRUL, lastName=Mamedov,
patronymic=dddddd, email=master555#gmail.com, phone=+99477777777,
password=$2a$11$txs/zdaLq.6eeBHz3uyM0e/R6uzJHs2.UIeIeRrV906y6Ia/hMOE6,
enabled=true, secret=MVNSUPKHWTAVLIEQ, country=Azerbaijan, state=Baki,
city=Badamdar, gender=Man, addressLine=GANJA, zipCode=2001,
birthDay=01-07-2020, passportSeria=AZE, passportNumber=1234567,
finCode=1234567, avatar=/resources/images/user-icon.png, mytext=null,
active=0, isUsing2FA=false, roles=[Role [name=ROLE_USER][id=5]])
For base authentication I use this project.
https://github.com/Baeldung/spring-security-registration
How to fix this error if it is a bug? I think password should't be shown anyway.
How get username?
How get other information if it possible? It is look like Array or some.property

I see you are using thymeleaf. Try this expression and instead of "getSomeProperty()" call any get method of your user class
${#authentication.getPrincipal().getSomeProperty()}

Thymeleaf Extras for Spring Security page on github explains somewhat more coherently, what sec:authentication tag attribute is supposed to convey - in short, e.g. <div sec:authentication="name"></div> is supposed to have the same meaning as <div th:text="${#authentication.name}"></div>, that is, they will both show the result of calling getName() on the Authentication object, that can be passed to a controller method automatically when using the Spring Security / Spring MVC framework, and inspected there.
Possibly, the OP was using a custom UserDetailsService, constructing his own User object, using some kind of toString() method for the username in the standard User(..) constructor - thus resulting in the above strange display. The User object returned from UserDetailsService seems to also be returned by getPrincipal() method of the Authentication object.
In any case, using ${#authentication} object properties as in the other answer, is a more fine-grained approach to getting all kinds of information for the logged-in user, not just the name (which can be rather ambiguous, as this question testifies)

Related

how to implement Single Responsibility in laravel

I am so confused about how to implement and how to follow SRP (single responsibility principle ) in a Laravel controller.
Suppose we have a controller which we have to do these things:
e.g
public function StorePost() {
// check user login()
//check number of current user Post count =>which must be less than 10
//store post
//send an email to user which your post has saved
//return =>api:json /web : redirect
}
I know that I can implement some DB queries in the repository but I don't know how to implement others of my logic code to achieve SRP
Also, I know there is a Heyman package to achieve these but I want to implement it by myself.
SRP in this context basically means each class and method should only be responsible for a single behaviour/feature. A rule of thumb is a class or method should change for one reason only, if it changes for multiple reasons, it needs to be broken down into smaller parts.
Your storePost method should not bother with checking the user login, that should be handled elsewhere before invoking storePost. storePost shouldnt change if the auth mechanism changes like switching from api token to json web token or something else. Laravel does this in the middleware level with the auth middleware.
Checking the users post count, this can be checked in the validation stage. storePost shouldn't change if we add more validation logic. In Laravel you can use FormValidation for this
For storing the post, the controller doesn't need to know how to call the DB, you can use the active record style using the model class or maybe create a service or repository class if your use case requires that. storePost shouldn't change if we decide to change DB vendor like going NoSQL.
For sending email, again the controller doesnt need to know how to send the email like what the subject/body recipients are. storePost shouldnt change if we need to change the email layout. Laravel has Notification for that
For serialising the response to json, the controller doesnt need to know how to format the response. if we decide to update how our json looks, storePost shouldnt change. Laravel has API Resources for that
So, ultimately in this example, the responsibility of the controller method is basically to glue all these together. It basically does what you wrote down, it only responsible for maintaining the step by step behavior, everything else is delegated to someone else. if the behavior change, like adding new behavior e.g notify all follower, storePost will change.

Know controller name in Codeigniter

For my Codeigniter (v 3.1.7) project, i create debug menu (like prestashop) with all informations of the login user, error of the page... to debug quickly the page.
So, i want to call the name of the controller and the name of the function.
If i'm on the page "login" i want to display:
Controller: Account
Function: Login
I find on this post i tips for my problem but we use Url REWRITING and the name of the url is not the real name of the controller.
If your CI version is below 3, you have to use like that:
$this->router->fetch_class();
$this->router->fetch_method();
and if your CI version is 3 or above. These methods are deprecated.
$this->router->fetch_class();
$this->router->fetch_method();
You can access the properties instead.
$this->router->class;
$this->router->method;
See codeigniter user guide
URI Routing methods fetch_directory(), fetch_class(), fetch_method()
With properties CI_Router::$directory, CI_Router::$class and CI_Router::$method being public and their respective fetch_*() no longer doing anything else to just return the properties - it doesn’t make sense to keep them.
Those are all internal, undocumented methods, but we’ve opted to deprecate them for now in order to maintain backwards-compatibility just in case. If some of you have utilized them, then you can now just access the properties instead:
$this->router->directory;
$this->router->class;
$this->router->method;
You could use the URI Class to get that information:
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

Spring Boot Data JPA tables with search, pagination and sorting

I'm developing an adminstration interface for a set of tables. I need to implement functionalities such as listing, sorting, filtering and pagination.
I'm using Spring Boot as a starter and Spring Data Jpa for repository. I've searched the Web for some examples about a complete solution that includes all the above functionalities. What I found included almost all of them, but appearently if there was pagination and sorting there wasn't filtering or viceversa.
Now I'm storing the filter in a application object on session using #ModelAttribute but I know that is now a good design because the applciation will extend and it becomes hard to maintain. I'm also using Page and Pagination for pagination purpose and using Specifications for filtering.
What I want is to submit all the data, i.e.: search fields, sorted fields and current page, in a single request. Off course if the search fields are not empty the pagination will be reinitialize.
Another thing is that I don't want to use jQuery datatables but plain HTML and form submission.
Here are some tutorials and examples that I found:
Link 1
Link 2
Thanks in advance
EDIT html form included
Here is the structure of my table and my pagination section:
<form method=post action=someLink>
<table> -populated from controller using Thymeleaf - </table>
<div class=pagination>
<ul> - actually this div is build using the page object returned from server -
<li><a href=link/?page=;size=;>1</a></li>
<li><a href=link/?page=;size=;>2</a></li>
<li><a href=link/?page=;size=;>3</a></li>
</ul>
</div>
</form>
As you can see the form is separated from my pagination div. When I click on a page number a get request is send to the server and executes the query with the stored filter. When I submit the form the page number is not taken into consideration because the number of pages can change.
So my question is how to build the form to include the pagination in one single submit.
I'm thinking instead of using a's to use input elements so on the server I can read the data from them. I don't know how to submit that post request with the pageable attributes.
Thanks
The first thing that you have to do is to enable Spring Data web support. If you are using Spring Boot, it's probably activated by Spring Boot.
After you have enabled the Spring Data web support, you can specify the current page, page size, and sorting options by settings the values of these request parameters:
The value of the page request parameter identifies the current page (this is zero indexed).
The value of the size request parameter defines the page size. The default page size is 20.
The value of the sort request parameter defines the sort options.
Spring Data JPA reference manual provides more information about the supported syntax.
You can now "inject" the requested page information into your controller method by adding a new org.springframework.data.domain.Pageable method parameter into your controller method. In your case, the controller method could look as follows:
#RequestMapping(value = "/search", method=RequestMethod.POST)
public String search(#ModelAttribute("searchFilter") FilterDTO filter, Pageable page) {
//Add logic here
return "results";
}

I want to change the home page menu depending on the login user. How do i do it in Spring MVC?

I am able to log-in using Spring-MVC.
Now i would like to change the menu's depending upon the user who logged in.
How do i pass login-username to my home page using spring MVC Controller?
So that i could use that UserName and change the menu according to Login-name?
Is there any framework available for same?
What if i want to send a collection of objects (Which will contain the actions assigned to the login user ) to my home page after successful login?
Is there any better way to do it?
any suggestions would be more appreciated. Need a Help.
If you want to handle this based on roles then spring security provides jsp taglib to handle this.
http://static.springsource.org/spring-security/site/docs/3.0.x/reference/taglibs.html
Example
<sec:authorize access="hasRole('supervisor')">
This content will only be visible to users who have
the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s.
</sec:authorize>
In addition to Bhushan's answer, you can also use your custom UserDetails class to store information pertaining to the authenticated user, and pass values to the model from your controller class with model.put("myParamName", myParam);
Then, in the JSP, with or without the authorize tag, you can refer to model attributes with ${myParam}. Note that this is not limited to pure HTML content; you may pass Javascript in this fashion as well -- just be wary of the fact that while what is passed may be whatever data type you like (that JSP can handle, anyway), it will be treated as a String when ultimately rendered, so you'll have to escape characters and include line breaks and/or tabs for lengthy content and proper formatting. For example:
MyController.java
. . .
String myJavascript = "<script>\n\tvar myVar = \"Hello Dheeraj!\";\n\talert(myVar);\n</script";
model.put("someJavascript", myJavascript);
. . .
myPage.jsp
${someJavascript}
Now, when that page is called, the client will see the following:
. . .
<script>
var myVar = "Hello Dheeraj!";
alert(myVar);
</script>
You can of course also pass arrays, etc., and loop through items to build <select> elements, etc. The user-specific logic will presumably reside on (or be called from) your controller class.

Spring security - same page to deliver different content based on user role

i tried to search for any previous post related to my issue but couldnt find any. I have a scenario where in page handles 3 different scenarios and one of them not working. This page returns different content depending on if the user is authenticated or anonymous.
localhost:8080/myApp/muUrl?test=authenticatedContent - > used for Scenario 1 & 2
localhost:8080/myApp/muUrl?test=anonymousContent -> used for Scenario 3
Scenario:
1) Authenticated user accesing the page url - the user gets displayed correct information. Works fine
2) Anonymous user accesing page URL with parameters that requires authentication - If anonymous, there is second level of check on the content they are accessing. for example, based on the GET parameters, there is custom logic to determine if the user has to be authenticated. In which case the page gets redirected to login page (WORKS fine).
3) Anonymous user accessing page URL with parameters that doesnt need authentication - in this case i get the SAvedRequest and redirect to the URL which is taking me to an infinite loop.
Am i missing something very obvious or is there a way in AuthenticationProcessFilterEntryPoint to say "DON'T redirect to LOGIN page but process it" ?
thanks.
I found a solution at last (someone suggested it to me on the Spring forums).
The idea is to use the #PreAuthorize annotation in the controllers as described here: see here
See code sample below:
#RequestMapping("/")
#PreAuthorize("isAuthenticated()")
public String authenticatedHomePage() {
return "authenticatedHomePage";
}
#RequestMapping("/")
public String homePage() {
return "homePage";
}

Resources