Symfony 2 - FOSUserBundle - how to integrate in API - api

I work on a new Symfony 2 project. I'm learning this framework at the same time. For the user management, I use the bundle FOSUserBundle.
My project works very well, I can login, register, logout and all other commands available.
The thing is that I want to make smartphone app which will use the API of my Symfony app. In the app, the user will have to sign in, or to sign up. Is it possible to use FOSUserBundle methods for API too?
I studied another bundle for making an API, it's FOSRestBundle.
If there are not solution, do you think that I will have to create my own users method like :
/api/login
/api/register
Then, inside this method, I redirect to FOSUserBundle methods? I'm just wondering what is the best, and the cleanest way to login, and register with FOSUserBundle from smartphone, so by using API

I have this problem too.
I found the best solution is this
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class YourController extends Controller{
//Other Methods..
public function loginAction(Request $request){
try{
$token = $this->get('security.authentication.manager')->authenticate(new UsernamePasswordToken('username', 'password', 'firewall'));
$this->get('security.context')->setToken($token);
}
catch(BadCredentialsException $e){
return new Response("Bad credentials", 403);
}
return new Response("success");
}
}

I used the FOSRestBundle.
This bundle is very powerful and simple to implement.
The documentation is pretty complete.
The github link of FOSRestBundle here
Hope that it helps

You need to check WSSE and how to integrate it to symfony.
Also check this post. And there is a bundle that implementing WSSE authentication. WSSE one of the best solutions for your app.

Related

Download File in Blazor Server Side with Authentication

I have a Blazor Server Side Web Application that uses the default authorization and authentication.
app.UseAuthentication()
app.UseAuthorization()
I can protect my pages with
#attribute [Authorize]
I have a login page with anonymous access to authenticate. This works fine.
Now I need a way to let the user download files from this authorized pages. Surprisingly I haven't found any straightforward way to do this.
One workaround is to build an API Controller with the filename as a path argument and give the user a link to it.
[Route("api/[controller]")]
public class FileController{
[HttpGet("download/{filename}")]
public async Task<IActionResult> Download([FromRoute] string filename){
//Do some checks and get file from Filesystem
return file;
}
}
And in the .razor file
private string CalculateDownloadLink(string filename){
return $"{NavigationManager.BaseUri}/api/file/download/{filename}"
}
This is a dumbed down version. In reality the filenames are generic. This works too.
Now I want to add Authentication to the API Controller because I don't want anyone guessing filenames. But I don't know how.
Of Course the [Authorize] Attribute doesn't work because the code is outside the circuit scope.
I can't figure out how to use any build-in Authorization to make this work.
Is there a better way to download files from a Blazor app?
A bit late answering your question, but [Authorize] on the controller should work. Have you tried it? Controller methods get the same cookies that Blazor pages get.
But there is a better way to download a file from Blazor without a need for navigation. See this blog post.
Your controller is not a controller. It does not implement Controller...
[Authorize]
public class FileController : Controller
{
...
}
FYI: If you add the download attribute to the anchor the file will only download when clicked.
<a download href="#CalculateDownloadLink("file.txt")">Download file.txt</a>
I made a junk repo that works if you need me to post it.

Symfony 3 functional test: authenticate user of own User class

I'd like to run functional tests on a section of my website which requires authentication. I found a solution for Symfony 2.x here. However, this does not work for Symfony3 as this line is now deprecated:
self::$kernel->getContainer()->get('security.context')->setToken($token);
My question is, how do I go around this and make it work with Symfony3? Thank you.
In Symfony 3, the SecurityContext was split into the TokenStorage and the AuthorizationChecker. Thus, you need to use the security.token_storage service:
self::$kernel->getContainer()->get('security.token_storage')->setToken($token);
However, a simpler approach would be to switch to HTTP Basic auth in your tests and configure the logged in user as described in http://symfony.com/doc/current/cookbook/testing/http_authentication.html.

Grails using Google authentication with the Spring Security plugin

Has anybody managed to successfully combine Google authentication with Burt Beckwith's awesome Grails-based Spring Security plugin recently? I wanted to go down that path with Grails 2.4.3, and after some fooling around (and recompiling the donbeave version of the plugin at https://github.com/donbeave/grails-spring-security-oauth-google) I was able to find a combination of references that would compile and run together. I ended up adding the following lines to my BuildConfig.groovy:
compile ':spring-security-core:2.0-RC4'
compile ":spring-security-oauth:2.1.0-RC4"
compile ':spring-security-oauth-google:0.3.1'
I found, however, that the changes created by the initialization command “grails s2-init-oauth” don’t give me all the modifications that I need in order to move forward. I ended up adding a block to my config.groovy that looked like this:
oauth {
providers {
google {
api = org.grails.plugin.springsecurity.oauth.GoogleApi20
key = 'MY KEY'
secret = 'MY SECRET'
successUri = '/oauth/google/success'
failureUri = '/oauth/google/error'
callback = "${baseURL}/oauth/google/callback"
scope = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email'
}
}
}
These config definitions specify a callback in my code (referred to above as ./oauth/google/callback) which didn’t exist. After I brought in a controller from the recommended example (https://github.com/bagage/grails-google-authentification-example), substituted "/springSecurityOAuth/onSuccess" for "/oauth/google/callback", (and registered by redirect URL through the Google Developers Console) I found that my onSuccess method was indeed being called, but the data structures referenced in the controller were wrong, and it seemed as if I would need to largely rewrite the controller logic in order to get everything working. I have to assume that other people want to accomplish Google-based authentication in the same way that I do. Is there an complete operational example somewhere? Or can someone tell me where I’ve gone wrong in my attempt to utilize the standard plug-ins? Thanks for any assistance.
You need to use spring security oauth plugin also. Please refer here https://github.com/cazacugmihai/grails-spring-security-oauth,
When you click on button, it hits the authenticate action inside Oauth controller which gets
authentication()
url of the google. After successful authentication, it hits callback() action Of Oauth controller which then redirects to onSuccess() action of SpringSecurityOauthController which then saves the info to OAuthId domain and finally redirects to the successUri given in config.

Tweeting from within meteor application

I am trying to build an app with Meteor that involves the user signing in with twitter, facebook, or google+, and then posting to those accounts from within the application.
First I'm trying to get twitter to work. I have my twitter sign in working, with the permission to tweet on their behalf working, but how to I actually send a tweet?
I think I need this: https://dev.twitter.com/docs/api/1.1/post/statuses/update but I can't figure out how the authentication works with Meteor.
Are there any examples that can help me here? Or tutorials?
You need an API to help you a bit unless you want to do it manually using REST with Meteor.http. I'd recommend you get meteorite: https://github.com/oortcloud/meteorite
Its installed like a node module via npm install -g meteorite
Meteorite is a wrapper for meteor that lets you use the community packages over at http://atmosphere.meteor.com
The twitter package you could use is twitter-api installed via mrt add twitter-api : https://github.com/Sewdn/meteor-twitter-api
Once added using the server api you can add a tweet via:
Server JS
var twitter = new Twitter();
Meteor.methods({
postTweet: function (text) {
if(Meteor.user())
twitter.postTweet(text),
return true;
}
});
Client JS
//Use this in your click handler where you want to post a tweet:
Meteor.call("postTweet", "This is Twweeeeeetttt!", function(err,result) {
if(!err) {
alert("Tweet posted");
}
});
The api takes care of the user's oauth tokens so you don't have to worry too much

Authentication for a Symfony2 api (for mobile app use)

I've developed a REST api for my Symfony2 application. This api will be used by a mobile app. Much of the functionality is done in the context of the currently authenticated user, ie:
$this->container->get('security.context')->getToken()->getUser()
I'm hoping that the mobile app will be able to post to the login action just like a traditional web form. If the credentials check out then Symfony2 does it's thing and sets a cookie (does this even work in the context of a mobile app accessing an api?). Then later api requests from that mobile phone will (hopefully) work with the native symfony2 security.context service container.
Would this work? I need to figure out this authorization process before I take the API to the mobile developers. If possible I'd obviously like to be able to use the native security.context service instead of building out a new auth system for the api that uses xAuth or something similar.
Thanks
I think you should do it stateless (without cookie).
I had the same problem, what i did:
in your app/config/security.yml, add:
security:
...
firewalls:
rest_webservice:
pattern: /webservice/rest/.*
stateless: true
http_basic:
provider: provider_name
...
Now you can make a request to your webservice:
class AuthTest extends WebTestCase
{
public function testAuthenticatedWithWebservice()
{
$client = $this->createClient();
// not authenticated
$client->request('GET', '/webservice/rest/url');
$this->assertEquals(401, $client->getResponse()->getStatusCode());
// authenticated
$client->request('GET', '/webservice/rest/url', array(), array(), array(
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'password'
));
$this->assertEquals(200, $client->getResponse()->getStatusCode());
}
}
Here you are, How to create a custom Authentication Provider awesome article.
To Authentication to a Symfony2 application through api, you need use:
WS-Security
Yes Marc, jules is pointing to an example just to show you how to test authentication with http_basic.
To be RESTful you should avoid using cookies, otherwise just call it an API. About how secure is your authentication system you can go with http_digest over https or more secure signed request with api_key/api_secret approach.
Have a look here http://wiki.zanox.com/en/RESTful_API_authentication