Categories
discuss

Difference between grant_type=client_credentials and grant_type=password in Authentication Flow?

I would like to understand the difference between grant_type=client_credentials and grant_type=password in Authentication or in OAuth2 Flow concept.

I am following below sites:

I presume grant_type=password is not secure way as far as using grant_type in JavaScript development. But I still wonder if someone can help me to understand this concept.

I also observed that grant_type=client_credentials doesn’t provide “refresh_token“, it only provides access_token where as grant_type=password provides both access_token and refresh_token.

Hoping to get detailed explanation. I am using WSO2 API Manager for OAuth2 for my application development

Answer

Resource owner credentials grant (password grant type)

When this grant is implemented the client itself will ask the user for their username and password (as opposed to being redirected to an IdP authorisation server to authenticate) and then send these to the authorisation server along with the client’s own credentials. If the authentication is successful then the client will be issued with an access token.

This grant is suitable for trusted clients such as a service’s own mobile client (for example Spotify’s iOS app). You could also use this in software where it’s not easy to implement the authorisation code – for example we bolted this authorisation grant into OwnCloud so we could retrieve details about a user that we couldn’t access over LDAP from the university’s Active Directory server.

Client credentials grant

This grant is similar to the resource owner credentials grant except only the client’s credentials are used to authenticate a request for an access token. Again this grant should only be allowed to be used by trusted clients.

This grant is suitable for machine-to-machine authentication, for example for use in a cron job which is performing maintenance tasks over an API. Another example would be a client making requests to an API that don’t require user’s permission.

When someone visits a member of staff’s page on the University of Lincoln staff directory the website uses its own access token (that was generated using this grant) to authenticate a request to the API server to get the data about the member of staff that is used to build the page. When a member of staff signs in to update their profile however their own access token is used to retrieve and update their data. Therefore there is a good separation of concerns and we can easily restrict permissions that each type of access token has.

Categories
discuss

How to setup Retrofit with no baseUrl

My apiPath is fully dynamic. I am having items containing fields such us “ipAddress” and “SSLprotocol”. Based on them I can build my url:

private String urlBuilder(Server server) {
    String protocol;
    String address = "";

    if (AppTools.isDeviceOnWifi(activity)) {
        address = serverToConnect.getExternalIp();
    } else if (AppTools.isDeviceOnGSM(activity)) {
        address = serverToConnect.getInternalIp();
    }

    if (server.isShouldUseSSL()) {
        protocol = "https://";
    } else {
        protocol = "http://";
    }
    return protocol + address;
}

So my protocol + address can be: http:// + 192.168.0.01:8010 = http://192.168.0.01:8010

And I would like to use it like that:

@FormUrlEncoded
@POST("{fullyGeneratedPath}/json/token.php")
Observable<AuthenticationResponse> authenticateUser(
            @Path("fullyGeneratedPath") String fullyGeneratedPath,
            @Field("login") String login,
            @Field("psw") String password,
            @Field("mobile") String mobile);

So full path for authenticateUser would be http://192.168.0.01:8010/json/token.php – for example.

That means I don’t need any basePath because I create whole basePath myself depending on server I want to connect to.

My retrofit setup is:

@Provides
@Singleton
Retrofit provideRetrofit(OkHttpClient okHttpClient,
            Converter.Factory converterFactory,
            AppConfig appConfig) {
    Retrofit.Builder builder = new Retrofit.Builder();
    builder.client(okHttpClient)
            .baseUrl(appConfig.getApiBasePath())
            .addConverterFactory(converterFactory)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

    return builder.build();
}

If I remove baseUrl then I get error that this parameter is required. So I set my apiBasePath to:

public String getApiBasePath() {
    return "";
}

And then I get error instantly after I create retrofit instance:

java.lang.IllegalArgumentException: Illegal URL: 

How to solve it?

Answer

From source (New URL resolving concept) you can simply specify whole path in post request.

Moreover we also can declare a full URL in @Post in Retrofit 2.0:

public interface APIService {

    @POST("http://api.nuuneoi.com/special/user/list")
    Call<Users> loadSpecialUsers();

}

Base URL will be ignored for this case.

Categories
discuss

vue.js Giving a value to a href in a tag

Sounds dumb but I can’t find a way to pass a variable data defined in the href:

ComponentFile.vue I tried all of those:

<a href=" url ">{{ url }}</a>
<a href=" {{ url }}">{{ url }}</a>
<a href=" {{ url }}">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>
<a @click=" url " v-bind:href="url"> {{ url }}</a>


...
export default {
        data() {
                   url: 'http://anywhere.com'
  }
}

What is the correct way?

Thanks!

Answer

You’ve defined data() as a function, but it isn’t returning anything. It should return an object with the data like so:

export default {
    data() {
        return {
            url: 'http://anywhere.com'
        }
    }
}

Then either of these will work:

<a href="{{url}}">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>

EDIT FOR VUE 2:

Interpolating variables in attributes is no longer recommended. Change:

<a href="{{url}}">{{ url }}</a>

To one of these:

<a :href="url">{{ url }}</a>
<a v-bind:href="url">{{ url }}</a>
Categories
discuss

How to pass default image to previous activity if no image is selected

In my app, I have a camera function. User can capture image or pick from gallery.

Activity B

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_LOAD_IMAGE:
                if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
                    selectedImage = data.getData();
                    imageView.setImageURI(selectedImage);
                }

                break;

            case REQUEST_IMAGE_CAPTURE:
                if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                    try {
                        selectedImage = imageUri;
                        getContentResolver().notifyChange(selectedImage, null);
                        imageView.setImageURI(null);
                        imageView.setImageURI(imageUri);
                    } catch (Exception e) {
                        Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                                .show();

                    }
                }
        }
    }

 submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent returnIntent = new Intent();
                if(selectedImage!=null) {
                    returnIntent.putExtra("img_uri", selectedImage.toString());
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

When submit button is clicked, it will return to previous activity.

Activity A

  @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
        if (resultCode == RESULT_OK) {
            if (requestCode == PROJECT_REQUEST_CODE) {
                imgURI = Uri.parse(data.getStringExtra("img_uri"));
                if (mClickedPosition == -1) { 
                    if (obj != null)
                        obj.addNewItem(imgURI);
                } else {
                    if (obj != null)
                     obj.changeItem(mClickedPosition, imgURI);
                }
            }
        }
    }

My question now is how to pass a default image to Activity A If user didn’t select any image ?

This is the xml imageView in Activity B

  <ImageView
                android:paddingTop="30dp"
                android:layout_gravity="center"
                android:layout_width="330dp"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"
                android:src="@mipmap/no_image"
                android:scaleType="fitXY"
                android:id="@+id/imageView"
                android:layout_weight="0.50" />

If no image selected, I want @mipmap/no_image return to Activity B. Is it possible ? Thanks.

Answer

You can pass an Uri of your image stored in resources by the next way:

submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent returnIntent = new Intent();
        if(selectedImage!=null) {
            returnIntent.putExtra("img_uri", selectedImage.toString());
        } else {
            returnIntent.putExtra("img_uri", Uri.parse("android.resource://your.package.name/mipmap/no_image").toString());
        }
        setResult(Activity.RESULT_OK, returnIntent);
        finish();
    }
});

Then you can use it as usual Uri to show the image in ImageView.

Categories
discuss

Custom ads on admob android studio based on keyword

I have searched online but had not luck so far in my research, I have set up admobs in my android app and now I only want relevant ads to show up based on keyword that I set. My app is based on toys, so I only want ads related to toys to show

 AdRequest adRequest = new AdRequest.Builder().build();
 adView.loadAd(adRequest);

Looking at this: Admob ad on custom Dialog

This person has used:

 AdRequest request = new AdRequest();
        Set<String> keywords = new HashSet<String>();
        keywords.add("game");
        request.setKeywords(keywords);

However, this does not work.

Answer

I think you need this:

AdRequest request = new AdRequest.Builder() 
.addKeyword("game").build();
.adView.loadAd(request);

You can try with this, but here are some examples, maybe you find what you allso need:

1.Test ads

Set up test ads by passing your hashed Device ID to AdRequest.Builder.addTestDevice:

 AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4")  // An example device ID
.build();

2.Location

Location targeting information may also be specified in the AdRequest:

AdRequest request = new AdRequest.Builder()
.setLocation(location)
.build();

3.Gender

If your app already knows a user’s gender, it can provide that information in the ad request for targeting purposes. The information is also forwarded to ad network mediation adapters if mediation is enabled.

AdRequest request = new AdRequest.Builder()
.setGender(AdRequest.GENDER_FEMALE)
.build();

4.Birthday

If your app already knows a user’s birthday, it can provide that information in the ad request for targeting purposes. This information is also forwarded to ad network mediation adapters if mediation is enabled.

AdRequest request = new AdRequest.Builder()
.setBirthday(new GregorianCalendar(1985, 1, 1).getTime())
.build();

5.Designed for Families setting

If you have opted your app in to Google Play’s Designed for Families program and you show ads in your app, you need to ensure those ads comply with the Designed for Families program requirements and ad policies.

Ad requests can be tagged as designed for families by setting the is_designed_for_families parameter to true in the extras:

Bundle extras = new Bundle();
extras.putBoolean("is_designed_for_families", true);

AdRequest request = new AdRequest.Builder()
    .addNetworkExtrasBundle(AdMobAdapter.class, extras)
    .build();

6.Child-directed setting

For purposes of the Children’s Online Privacy Protection Act (COPPA), there is a setting called “tag for child directed treatment”.

As an app developer, you can indicate whether you want Google to treat your content as child-directed when you make an ad request. If you indicate that you want Google to treat your content as child-directed, we will take steps to disable IBA and remarketing ads on that ad request. The setting can be used with all versions of the Google Play services SDK, via AdRequest.Builder.tagForChildDirectedTreatment(boolean):

If you set tagForChildDirectedTreatment to true, you will indicate that your content should be treated as child-directed for purposes of COPPA. If you set tagForChildDirectedTreatment to false, you will indicate that your content should not be treated as child-directed for purposes of COPPA. If you do not set tagForChildDirectedTreatment, ad requests will include no indication of how you would like your content treated with respect to COPPA.

AdRequest request = new AdRequest.Builder() .tagForChildDirectedTreatment(true) .build();

By setting this tag, you certify that this notification is accurate and you are authorized to act on behalf of the owner of the app. You understand that abuse of this setting may result in termination of your Google account.

7.Keyword

Add a keyword for targeting purposes.

AdRequest request = new AdRequest.Builder() .addKeyword(someKeyword) .build();

Loading an ad with targeting

Once your request targeting information is set, call loadAd on the AdView with your AdRequest instance.

AdRequest request = new AdRequest.Builder()
.setLocation(location)
.setGender(AdRequest.GENDER_FEMALE)
.setBirthday(new GregorianCalendar(1985, 1, 1).getTime())
.tagForChildDirectedTreatment(true)
.addKeyword("game")
.build();
adView.loadAd(request);

Additional information can be found on this link.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..